Lambdas: local variables need final, instance variables don't

Gerard picture Gerard · Jul 31, 2014 · Viewed 77.4k times · Source

In a lambda, local variables need to be final, but instance variables don't. Why so?

Answer

Adam Adamaszek picture Adam Adamaszek · Jul 31, 2014

The fundamental difference between a field and a local variable is that the local variable is copied when JVM creates a lambda instance. On the other hand, fields can be changed freely, because the changes to them are propagated to the outside class instance as well (their scope is the whole outside class, as Boris pointed out below).

The easiest way of thinking about anonymous classes, closures and labmdas is from the variable scope perspective; imagine a copy constructor added for all local variables you pass to a closure.