Function as an expression

While writing the function, you need to put the code in a function body. However, in Kotlin, you can define a function as an expression. For example: you want to find the minimum between two numbers and you wrote a function called min() as follows: 

fun main(args: Array<String>) {
print(min(4,7))
}
fun min(numberA: Int, numberB:Int) : Int {
if(numberA < numberB){
return numberA
}else{
return numberB
}
}

This will return the minimum number out of two given numbers. This function can be written as an expression style as follows:

fun min(numberA: Int, numberB:Int) : Int = if(numberA < numberB){ numberA }else{ numberB }

This is how the code looks expressive and compact. Also, notice that we have removed the return keyword, as Kotlin is smart enough to return the last value without explicitly specifying the return keyword. This is what is called a single line or one line function. However, for a complex function, you can write it in multiple lines as follows:

fun min(numberA: Int, numberB:Int) : Int
= if(numberA < numberB){
numberA
}else{
numberB
}

This looks more compact and expressive.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.3.104