Why the code in an object expression can access variables from the scope that contains it in kotlin?

后端 未结 5 1185
醉梦人生
醉梦人生 2021-01-01 10:49

In Kotlin,the code in an object expression can access variables from the scope that contains it, just like the following code:

fun countClicks(window: JCompo         


        
5条回答
  •  甜味超标
    2021-01-01 11:44

    The concept you're referring to is called "capturing".

    There's a trick that can be applied in Java: Wrap the mutable value into a final wrapper such as AtomicReference and the compiler will stop complaining:

    AtomicReference max = new AtomicReference<>(10);
    if (System.currentTimeMillis() % 2 == 0) {
        max.set(11)
    }
    Predicate pred = i -> i * 2 > max.get();
    

    That's basically what's happening in Kotlin as well: If a final variable (val) is being captured, it simply gets copied into the lambda. But if, on the other hand, a mutable variable (var) is being captured, its value is wrapped in an instance of Ref:

    class Ref(var value: T)
    

    The Ref variable is final and therefore can be captured without a problem. As a result, the mutable variable can be changed from within the lambda.

提交回复
热议问题