In Kotlin, a lambda is an anonymous function that can be treated as a value.
// CharSequence.count(predicate: (Char) -> Boolean)
"A link to the past".count({ letter -> letter == 't' }) // 3
// We can remove the `()` when the last argument is a function
println("A link to the past".count {
letter -> letter == 't'
})
/*
** When using lambda with a single argument,
** you can either give the argument a name or use the `it` keyword
** as a shorthand way to refer to the argument.
*/
"A link to the past".count { it == 't' } // 3💡 A
returninside a lambda expression will return from the enclosing function.
Syntax
// The value of the last expression is implicitly returned.
val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
// Removing optional annotations out
val sum = { x: Int, y: Int -> x + y }Anonymous functions
val nums = arrayListOf(1,2,3,4,5)
nums.filter(fun(item) = item > 3)) // [4, 5]💡 A
returnstatement without a label always returns from the function declared with thefunkeyword.
Closures
Kotlin functions can access its closure, which includes the variables declared in the outer scope.
val nums = arrayListOf(1,2,3,4,5)
var sum = 0
nums.filter { it > 0 }.forEach {
sum += it
}
print(sum) // 15