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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access