Lambda (Kotlin)
A lambda is an anonymous function written in braces, like { x -> x + 1 }. Lambdas are the values you pass to higher-order functions and are the backbone of Kotlin's collection operations.
Kotlin
A lambda is enclosed in { }, with parameters before -> and the body after; the last expression is its return value. When a lambda has a single parameter you can omit it and use the implicit name it, giving the concise { it * 2 }.
If a function's last parameter is a lambda, you can write it outside the parentheses (trailing-lambda syntax), and if it's the only parameter you drop the parentheses entirely: list.map { it.name }. This is why so much Kotlin reads like a fluent DSL.
Lambdas capture variables from their enclosing scope (closures). For simply forwarding to an existing function, function references like ::println or String::uppercase are an even shorter alternative.
Syntax
val square = { x: Int -> x * x }
list.filter { it > 0 }Examples
Kotlin
val nums = listOf(1, 2, 3, 4)
val evens = nums.filter { it % 2 == 0 }
println(evens)Output:
[2, 4]