Closures

Lambdas Capture Variables

A lambda can read and modify variables from the scope where it was created. The lambda "closes over" them, so it is called a closure. (Unlike Java, the variables do not need to be final.)

Example

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

fun main() {
    var total = 0
    listOf(100, 250, 75).forEach { total += it }
    println("Total: $total")

    val clicks = makeCounter()
    val views = makeCounter()
    clicks(); clicks(); clicks()
    views()
    println("clicks=${clicks()} views=${views()}")
}

Output

Total: 425
clicks=4 views=2