Skip to content

Lambdas and inline ​

kotlin
// Lambdas, closures that capture mutable state, function references, inline functions
// with non-local return, and scope functions.

fun makeCounter(): () -> Int {
    var n = 0                      // captured and mutated: lives in a shared heap cell
    return { n += 1; n }
}

fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { x -> g(f(x)) }

fun double(x: Int) = x * 2

inline fun twice(action: () -> Unit) {
    action()
    action()
}

fun firstBig(xs: List<Int>): String {
    xs.forEach { if (it > 10) return "big: $it" }   // non-local return from an inline lambda
    return "none"
}

fun main() {
    val c1 = makeCounter()
    val c2 = makeCounter()
    println("${c1()} ${c1()} ${c1()} ${c2()}")

    val addThree = { x: Int -> x + 3 }
    println(compose(addThree, ::double)(4))

    var log = ""
    twice { log += "x" }
    println(log)

    println(firstBig(listOf(1, 20, 30)))
    println(firstBig(listOf(1, 2)))

    println(5.let { it + 1 })
    println("abc".also { println("also $it") }.length)
    println(StringBuilder().apply { append("a"); append(1) }.toString())
    println(with("hello") { uppercase() })
}

Output:

text
1 2 3 1
14
xx
big: 20
none
6
also abc
3
a1
HELLO

Notes ​

  • A lambda that is not inlined becomes a small object (a closure) with one field per captured value. A captured var such as n in makeCounter lives in a shared heap cell that the function and all closures use.
  • A call of an inline function is expanded in place together with the lambda passed to it. No closure object is created, captured variables are used directly, and return inside the lambda returns from the enclosing function (firstBig).
  • Limits: an inline lambda parameter may only be invoked or passed to another inline function. Store it by declaring the parameter noinline.
  • Scope functions (let, also, apply, with, run) are ordinary stdlib source and are inlined.

See Closures and inline.

Released under the Apache License 2.0.