Single-expression functions

Until now, all our examples were declared in a normal way.

The function sum takes two Int values and adds them. Declared in a normal way, we must provide a body with curly braces and an explicit return:

fun sum(a:Int, b:Int): Int {
return a + b
}

Our sum function has its body declared inside curly braces with a return clause. But if our function is just one expression, it could have been written in a single line:

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

So, no curly braces, no return clause, and an equals (=) symbol. If you pay attention, it just looks similar to a lambda. 

If you want to cut even more characters, you can use type inference too:

fun sum(a:Int, b:Int) = a + b
Use type inference for a function's return when it is very evident which type you are trying to return. A good rule of thumb is to use it for simple types such as numeric values, Boolean, string, and simple data class constructors. Anything more complicated, especially if the function does any transformation, should have explicit types. Your future self will be glad!
..................Content has been hidden....................

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