Function as an expression

In Kotlin, a function can behave as an expression. Let's take the example of the add function from the previous section and convert it into an expression:

fun addValues(i: Int, j: Int): Int {
return i + j
}

This function takes two parameters, adds them, and returns an integer value. When the function contains only one line of code, it can be written as an expression. 

Create a new function as an expression:

fun addValuesEx(a : Int, b : Int) : Int = a + b

The explicit declaration of the function return type can be removed as follows:

fun addValuesEx(a : Int, b : Int) = a + b

Now add an equals operator, remove the curly brackets, and remove the explicit type declaration of the return type along with the return keyword from the function body. The compiler will figure out the return type by itself. Next, call addValues and addValuesEx in our main. Verify the output of each function:

fun addValues(i: Int, j: Int): Int{
return i + j
}

fun addValuesEx(a : Int, b : Int) = a + b

fun main (args: Array<String>) {
var result = addValues(5,6)
println(result)

result = addValuesEx(5,6)
println(result)
}

Take another example. Write a function that takes two integer variables and returns the highest one. Return any value if both values are same:

fun getMaxEx(x: Int, y: Int) =
if(x >= y){
x
} else {
y
}

fun main (args: Array<String>) {
var val1 = 8
var val2 = 6

max = getMaxEx(val1,val2)
println("$val1 , $val2 : Max value is $max")
}

Writing a function as an expression always helps to remove unwanted code, but sometimes this convenience can be problematic. Add minor changes in the following function by adding a string value in if and else statements and executing it:

 fun getMaxExx(x: Int, y: Int) =
if(x >= y){
x
"Scary"
} else {
y
"Yes it is"
}

fun main (args: Array<String>) {
var val1 = 8
var val2 = 6
var maxEx = getMaxExx(val1,val2)
println("$val1 , $val2 : Max value is $maxEx")
}

This function returns Scary as output. When a function is written as an expression and no return type is defined in the function signature, the type inference comes into action, which means that Kotlin always returns the last line of code and the compiler evaluates the return type at runtime. If the line is an integer or a string, it will be decided accordingly. In this example, the expected output is an integer, but a string is returned. This tricky situation can be overcome by declaring the function return type:

fun getMaxEx(x: Int, y: Int) : Int =
if(x >= y){
x
"Scary"
} else {
y
"Yes it is"
}

If the return value is anything other than declared type, the compiler will throw the following error:

Type mismatch: inferred type is String but Int was expected
..................Content has been hidden....................

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