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 methodcan mutate
  2. A static variablecan mutate
  3. A local variablecan’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

Local variables referenced from a lambda expression must be final or effectively final

Local variables referenced from a lambda expression must be final or effectively final

effectively final :

  • A variable or parameter whose value is never changed after it is initialized
  • If a reference is not changed it is effectively final even if the object referenced is changed.
  • Any variable that is assigned once and only once, is “effectively final”.

In simple terms :

Imagine adding the final modifier to a variable declaration. If, with this change, the program continues to behave in the same way, both at compile time and at run time, then that variable is effectively final.

It looks like it is exact similar way. But only difference is no final keyword.

eg :

these are final

final int variable = 123;

final int number;
number = 23;

this is effective final

int variable = 123;

int number;
number = 34;

Fruther discussion :

Variables inside anonymous class must be final in outer class

#effectively-final, #final, #lambda