TExcelTAD
Home › Kotlin › Kotlin Lambdas & Higher-Order Functions

Kotlin Lambdas and Higher-Order Functions

In Kotlin, functions are first-class values: you can store them in variables, pass them to other functions and return them. A lambda is a function literal written inline, and a higher-order function is a function that takes or returns other functions. You've already used them: filter { it > 5 } passes a lambda to filter.

Lambda syntax

A lambda is written in curly braces: parameters, an arrow ->, then the body. The value of the last expression is returned.

kotlin · try it yourself
fun main() {
    val add = { a: Int, b: Int -> a + b }
    val greet = { name: String -> "Hi, $name!" }
    val shout: (String) -> String = { it.uppercase() + "!" }

    println(add(2, 3))
    println(greet("Rui"))
    println(shout("hey"))
}
5
Hi, Rui!
HEY!

Function types

Function types describe parameters and return type: (Int, Int) -> Int. A function that takes nothing and returns nothing is () -> Unit.

Type Example value
() -> Unit { println("tick") }
(Int) -> Boolean { it > 0 }
(String, Int) -> String { s, n -> s.repeat(n) }
((Int) -> Int)? a nullable function

If a lambda has exactly one parameter whose type the compiler knows, you can skip declaring it and use the implicit name it.

Writing a higher-order function

kotlin · try it yourself
fun applyTwice(x: Int, f: (Int) -> Int): Int = f(f(x))

fun repeatAction(times: Int, action: (Int) -> Unit) {
    for (i in 1..times) action(i)
}

fun main() {
    println(applyTwice(3) { it * 10 })
    println(applyTwice(5) { it - 1 })
    repeatAction(3) { i -> println("Round $i") }
}
300
3
Round 1
Round 2
Round 3

Trailing lambda syntax: when the last parameter is a function, the lambda can go outside the parentheses: applyTwice(3) { it * 10 }. If it's the only argument, the parentheses disappear completely — that's why we write list.filter { … }.

Function references

Use ::name to pass an existing function where a lambda is expected:

kotlin · try it yourself
fun isVowel(c: Char) = c.lowercaseChar() in "aeiou"

fun main() {
    val text = "Higher Order"
    println(text.filter(::isVowel))
    println(listOf("1", "22", "333").map(String::length))
    println(listOf(4.0, 9.0, 16.0).map(Math::sqrt))
}
ieOe
[1, 2, 3]
[2.0, 3.0, 4.0]

Returning functions and closures

A function can return a lambda. The lambda captures variables from the scope where it was created — that's a closure:

kotlin · try it yourself
fun multiplier(factor: Int): (Int) -> Int = { it * factor }

fun makeCounter(): () -> Int {
    var count = 0
    return { ++count }
}

fun main() {
    val triple = multiplier(3)
    println(triple(7))

    val next = makeCounter()
    println(next())
    println(next())
    println(next())
}
21
1
2
3

Each counter keeps its own count alive, even after makeCounter returned.

Destructuring and unused parameters

Lambdas can destructure pairs and map entries, and _ marks a parameter you don't need:

kotlin · try it yourself
fun main() {
    val scores = mapOf("Ann" to 82, "Bo" to 67, "Cai" to 91)
    scores.forEach { (name, score) -> println("$name: $score") }
    println(scores.filter { (_, score) -> score > 80 }.keys)
    println(scores.map { (name, _) -> name.length }.sum())
}
Ann: 82
Bo: 67
Cai: 91
[Ann, Cai]
8

Returning from a lambda

A bare return inside a lambda returns from the enclosing function (only allowed when the lambda is inlined). To return from just the lambda, use a label: return@forEach, return@map, or the value of the last expression.

kotlin
listOf(1, -2, 3).forEach {
    if (it < 0) return@forEach   // skip negative numbers
    println(it)
}

Tip: Standard-library higher-order functions like filter, map and let are inline: the compiler copies the lambda into the call site, so there's no runtime overhead for using them.

Test yourself

What is the type of { s: String -> s.length }?

  1. (Int) -> String
  2. (String) -> Int
  3. String -> Int
  4. () -> Int

When can you use it in a lambda?

  1. Always
  2. When the lambda has exactly one parameter
  3. Only in forEach
  4. When the lambda has no parameters

What does ::isEven mean?

  1. Call isEven now
  2. A reference to the function isEven
  3. A static import
  4. A label