Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 10 / Topic 1 of 8

Lambdas, properly this time

Part 6 used { it > 100.0 } as an argument to filter/map/sumOf without naming what it was. A lambda is { parameters -> body } — and crucially, it's a value: something you can store in a val, pass around, and call later, just like any other value.

val isExpensive: (Double) -> Boolean = { price -> price > 500.0 }
println("isExpensive(650.0): ${isExpensive(650.0)}")

val isCheap: (Double) -> Boolean = { it < 100.0 }     // single param -- drop the name, use `it`
println("isCheap(80.0): ${isCheap(80.0)}")
isExpensive(650.0): true
isCheap(80.0): true

When a lambda is the last argument to a function, it can move outside the parentheses — "trailing lambda syntax." prices.filter({ it > 500.0 }) and prices.filter { it > 500.0 } are the exact same call; the second is just how it's normally written.

val classify: (Double) -> String = { price ->
    val gst = price * 0.18
    if (price > 500.0) "Expensive (GST ₹%.2f)".format(gst) else "Affordable"
}
println(listOf(650.0, 80.0, 1200.0, 45.0).map(classify))
[Expensive (GST ₹117.00), Affordable, Expensive (GST ₹216.00), Affordable]

A lambda body can hold multiple statements; whatever the last expression evaluates to is what the lambda returns. And like any inner function, a lambda captures variables from its enclosing scope — it can read them, and if they're a var, change them too.

Full program: examples/01_lambdas_recap.kt.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide