When passing a variable (an int or some immutable type) to a block of the lambda expression, if it is..
- An instance variable and lambda block is also inside a instance method โ can mutate
- A static variable โ can mutate
- A local variable โ canโt mutate
Root cause :
Here, Java would need to capture a reference, and then modify the value through it.
And JVM lacks mechanisms of constructing references to local variables.
Thatโs why #3 doesnโt work.
Java does not have this problem when you use an array, because arrays are reference objects.
Because Java can capture array reference that never changes, and use that non-changing reference to mutate the object.
Java arrays are mutable.
And a reference to the static variable is readily available, so there is no problem with capturing it. Thatโs why #2 works.
And Lambda modifies the variable through this object. thatโs why #1 works
References :
- https://stackoverflow.com/questions/40862845/java-8-lambda-variable-scope
- https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Benefits-of-lambda-expressions-in-Java-makes-the-move-to-a-newer-JDK-worthwhile