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
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.