kotlinlambda

Capture and mutate value of variable outside lambda expression


Is it possible to increment the value of the counter variable in the main function from a lambda?

fun main(){
   var counter = 0
   val incr = { ++counter}
   incr
   println(counter)

Solution

  • Well, you can misuse an anonymous function and hand over the variable that should get modified. But I am not sure that is what you are looking for:

    fun main() {
        var counter = 0
        val incr = { _: Int -> ++counter }
        incr(counter)
        println(counter)
    }
    

    The output is actually 1.