Skip to content
Lambdas and Higher-Order Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions and Lambdas

Lambdas in Kotlin use { params -> body } syntax. They're first-class values you can pass around, store, and return.

val double: (Int) -> Int = { n -> n * 2 }
val add: (Int, Int) -> Int = { a, b -> a + b }
println(double(5))         // 10
println(add(3, 4))         // 7

When a lambda is the LAST argument to a function, it can be moved outside the parens:

[1, 2, 3].map { it * 2 }                 // {} outside, no extra parens needed
[1, 2, 3].map({ it * 2 })                // also valid (less idiomatic)

A function that takes another function is higher-order:

fun applyTwice(n: Int, op: (Int) -> Int) = op(op(n))
println(applyTwice(3) { it * it })   // 81 — (3*3)*(3*3)

Kotlin's standard library is built around this — map, filter, forEach, let, apply, also, run, with are all higher-order.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…