Why must the variables a Java lambda captures be effectively final, and what does effectively final actually mean?
Because a lambda takes a copy of the value of the variable, and the rule stops you from changing that copy in a way that depends on timing.
What effectively final means is simple. The variable is never given a new value after it has been created. It does not have to be marked with the word final, it only has to be left alone.
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
int base = 10;
// This is fine, because base is never given a new value.
Supplier<Integer> read = () -> base;
System.out.println("the value : " + read.get());
// This would not compile:
// base = 20;
// The message says that base must be final or effectively final.
}
}
So why does the rule exist? Because a lambda does not run straight away. The body of a lambda may run long after the method that made it has returned, and it may run on a different thread. If the lambda could see a variable that had been given a new value, it would have no way of knowing which value it was supposed to use, and the answer would depend on when the lambda happened to run.
Notice that the rule is about the variable and not about the object. It is perfectly legal to capture an object and to change the contents of that object inside the lambda. What you may not do is point the variable at a different object.
The next question in this topic looks at the ways round it.