Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit being able to use effectively final variables in Java 8 lambda expressions

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?

like image 526
Louise Miller Avatar asked Dec 01 '22 19:12

Louise Miller


2 Answers

The simple answer is, since there is no difference between final and “effectively final” variables, besides the keyword final in their declaration, the only purpose is to allow omitting the final 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 a final declaration to the x 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 add final and a type declaration to the parameter turning the simple expression x -> 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.

like image 110
Holger Avatar answered Dec 04 '22 10:12

Holger


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.

like image 42
Brian Goetz Avatar answered Dec 04 '22 11:12

Brian Goetz