Mohammadreza Khahani
12/31/2023, 4:35 PMfun 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
}Youssef Shoaib [MOD]
12/31/2023, 4:54 PMclass 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
}Mohammadreza Khahani
12/31/2023, 5:15 PMcount 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.Landry Norris
12/31/2023, 5:44 PMYoussef Shoaib [MOD]
12/31/2023, 5:49 PMreturn 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.