0

The difference of a local variable being final or effectively final has been discussed here. I do not really understand though, why it was introduced in Java 8. To me it seems like it just gives the programmer the freedom to leave out the final keyword, but treating the variable effectively as final. No change in logic, just a helper for the 'lazy' programmer not to need to write final.

Isn't that even a step-back, since now a variable that is effectively final misses the keyword, not indicating it to the reader of the code. So is there a reason for Oracle to allow leaving out the final keyword here?

Community
  • 1
  • 1
Mathias Bader
  • 3,585
  • 7
  • 39
  • 61
  • 1
    It was not introduced. What was introduced was the ability to access such variables from a Lambda expression. `Effectively final` is just a way to describe variables that don't actually change, and those existed in Java since it was created. – RealSkeptic Nov 03 '14 at 13:51
  • http://stackoverflow.com/questions/20938095/difference-between-final-and-effectively-final – Akshay Nov 03 '14 at 13:51
  • Less code saying more is not called "laziness", but "expressiveness". Thankfully, Java has begun to appreciate that virtue. – Marko Topolnik Nov 03 '14 at 13:59
  • 1
    @Holger this question was not really a duplicate. The question to which you redirected asked, _What_ is the difference. This question asks _why?_ – Solomon Slow Nov 03 '14 at 15:36
  • @james large: maybe you read more carefully. The question I linked is *exactly about WHY*. The question about the difference, which *others* have linked to, is another question. – Holger Nov 03 '14 at 16:06
  • @Holger Yes, it's almost an *uncanny* duplicate, and my answer a duplicate of yours :) – Marko Topolnik Nov 03 '14 at 16:28

1 Answers1

4

Closures in Java (existing since version 1.1) can only close over final variables. With the helplessly verbose syntax of anonymous classes the few additional final modifiers were not such a big deal (although they did make for an occasional surprise when they jumped at you in parameter lists), but with the new concise lambda syntax, they are. They would also cause lambdas to less seamlessy blend into the fabric of the code. Especially consider the case of nested lambdas:

new TreeSet<Integer>((a, b) -> uncheckCall(() -> exceptionThrowingMethod(a, b)))

compared with

new TreeSet<Integer>((final Integer a, final Integer b) -> 
     uncheckCall(() -> exceptionThrowingMethod(a, b))
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436