Hello, brilliant Kotlin developers. Could someone ...
# getting-started
m
Hello, brilliant Kotlin developers. Could someone explain how this closure function works?🙏
Copy code
fun createIncrementFunction(incrementBy: Int): () -> Int {
    var count = 0

    return {
        count += incrementBy
        count
    }
}

fun main() {
    val incrementByTwo = createIncrementFunction(2)
    println(incrementByTwo()) // Output: 2
    println(incrementByTwo()) // Output: 4
}
y
It's equivalent to this class:
Copy code
class Incrementer(private val incrementBy: Int) {
    private var count = 0

    operator fun invoke(): Int {
        count += incrementBy
        return count
    }
}

fun main() {
    val incrementByTwo = Incrementer(2)
    println(incrementByTwo()) // Output: 2
    println(incrementByTwo()) // Output: 4
}
👍 1
m
It clarifies the example, now the only question left is how the
count
becomes part of the returned lambda function or where the
count
state is preserved? In the class example, the state of
count
is preserved in the
incrementByTwo
variable but in the original example, the returned value is a lambda function of type
() -> Int
.
l
You'd have to check the bytecode to know for sure, but it may create an actual class under the hood like shown above that holds the captured value.
y
That is exactly what it does! Basically, the lambda that gets
return
is what's called a closure. What happens under the hood is that
count
is converted to an
IntRef
, which is a class that holds a single
var
.
👏 1