Closures

If you are not familiar with the concept of a closure, the easiest way to describe it would be as a scope (function) that can access the state (variables) of another scope. When you define local variables inside a function, then their scope is the body of that function. A function can also declare a lambda expression, which has its own scope. You can access local variables of the outer function from the lambda expression. This is a closure.

Java also supports a closure with anonymous classes and lambdas. But, there is one big difference between Kotlin and Java. When Java closes over a variable, it captures its value. That's why you can only close over variables that have the final modifier, that is, they are immutable.

The following example tries to modify a local variable from an anonymous class, but the compiler will throw an error here because the local variable is not final:

int a = 0;
Runnable runnable = new Runnable()
{
@Override
public void run() {
a++; //compiler error
}
};

But, if you put the final modifier into a variable, then you won't be able to modify it. So, the trick is to wrap the variable inside a final one-sized array or the AtomicReference type:

final int[] a = { 0 };
Runnable runnable = new Runnable() {
@Override
public void run() {
a[0]++;
}
};

In Kotlin, there are no restrictions like in Java. You can access non-final variables inside a closure and also modify them. Similar code in Kotlin shows this:

var a = 0
val closure = {
a++
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.208