Lambdas

A lambda is a function that is not declared. This is useful when we need to invoke an action, but we don't need to define a function for it, because we will use it only once, or only in one scope. A lambda is an expression, meaning that it returns a value. All of the functions in Kotlin are expressions, and even a scope of a function doesn't contain the return keyword; it returns a value that is evaluated at the end.

The following lambda expression returns an object of the Unit type, implicitly:

{x: Int -> println(x)}

A declaration of the Unit object looks as follows:

public object Unit {
override fun toString() = "kotlin.Unit"
}

A reference to a lambda can be saved to a variable:

val predicate: (Int) -> Unit = { println(it) }

We can use this variable to invoke the saved lambda:

predicate(3)
..................Content has been hidden....................

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