Lambda Expressions

Functions as Values

A lambda is a small function without a name, written in curly braces: { parameters -> body }. The last expression in the body is the return value (no return keyword). You can store a lambda in a variable and call it like a function.

Example

fun main() {
    val greet = { name: String -> "Hello, $name!" }
    val add = { a: Int, b: Int -> a + b }
    val sayHi = { println("Hi there") }      // no parameters

    println(greet("Anjali"))
    println(add(4, 6))
    sayHi()
}

Output

Hello, Anjali!
10
Hi there

The it Parameter

If a lambda has exactly one parameter and its type can be inferred, you can skip declaring it and use it.

Example

fun main() {
    val prices = listOf(120, 450, 80, 999)
    println(prices.filter { it > 100 })              // it = each price
    println(prices.map { price -> price * 2 })       // explicit name is clearer for longer lambdas
    val square: (Int) -> Int = { it * it }
    println(square(9))
}

Output

[120, 450, 999]
[240, 900, 160, 1998]
81

Tip: Use it in short, one-line lambdas. In nested or longer lambdas, give the parameter a real name.