I have understand what "effectively final" means as explained by Difference between final and effectively final.
What I dont understand is why use of effectively final variables would be desired for lambda expressions/annoymous inner classes ? Why would Java 8 loosen its restriction that the variables must be declared final?
Is it just to save the typing of final
before the variable? Or does ability of being able to use effectively final variables have some other advantage?
You can think of this as extending the scope of type inference in Java to include inferring finality of local variables for purposes of capture within lambda expressions and inner classes. The rule hasn't changed -- lambdas and inner classes capture values, not variables -- but the syntactic burden of conforming to the rule has been lessened.
The simple answer is, since there is no difference between
final
and “effectively final” variables, besides the keywordfinal
in their declaration, the only purpose is to allow omitting thefinal
keyword.But this might have more impact than you are aware of.
For a lambda expression, the entire declaration of the parameter(s) can be simplified as in
x -> x+1
. Now consider nested lambda expressions like:x -> y -> x+y
and the visual clutter which would be created if we were enforce to add afinal
declaration to thex
parameter here.Since there is no Java syntax to declare a variable as
final
without specifying its type it would either require the specification to add an even more complex construct to the language or enforce us to addfinal
and a type declaration to the parameter turning the simple expressionx -> y -> x+y
into(final double x) -> y -> x+y
.The main goal was to provide a simplification to the Java programmer (as far as this is possible when adding a new programming language feature). Surely it doesn’t offer any feature to the language for solving problems which couldn’t be solved before without it (this holds for the entire lambda feature), but there is a notable gain in expressiveness not only because you can omit
final
modifiers but it helps. It works together with the improved type inference, new programming APIs and, of course, lambda expressions and method references.