June 2018
Intermediate to advanced
316 pages
6h 34m
English
A closure is a function that has access to variables that are defined in the outer scope. In our example, the { p1: P1 -> this(f(p1)) } closure captures the f: (P1) -> R1 argument. Unlike in Java, variables captured in a closure can be modified in Kotlin. The following example shows how to modify a captured variable in Kotlin:
var totalAges = 0students.forEach { totalAges += it.age}
But in Java, this similar example will lead to a compilation error:
int totalAges = 0;students.forEach(student -> totalAges += student.getAge());
The compilation error will read:
Error:(19, 49) java: local variables referenced from a lambda expression must be final or effectively final
Read now
Unlock full access