Passing a variable (an int or some immutable type) to a Lambda block

When passing a variable (an int or some immutable type) to a block of the lambda expression, if it is..

  1. An instance variable and lambda block is also inside a instance method – can mutate
  2. A static variable – can mutate
  3. 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

#lambda, #references