-
Book Overview & Buying
-
Table Of Contents
Android Programming for Beginners - Fourth Edition
By :
Here is a very basic lambda expression that takes 2 numbers as parameters, adds them together, and returns the result.
val sum =
{ a: Int, b: Int ->
a + b
}
We could also write the type explicitly as val sum: (Int, Int) ‑> Int, but Kotlin infers it for us.
In this code, we create a lambda with two parameters, a and b, both of type Int. Inside the body of the lambda, we add a and b. Since a + b is the last (and only) line of the lambda body, much like regular functions, this expression will be the return value of the lambda.
Notice the first line of code:
val sum =
This may seem unusual at first, but it's essential to understand that sum is not an Int type. It is a variable that holds a reference to a lambda. But what exactly is its type then?
The type of sum is a lambda function. More specifically, its type is a lambda function that matches the parameters and return type of the lambda. So, sum is a lambda function that takes two...