问题
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?
回答1:
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))
来源:https://stackoverflow.com/questions/26715689/why-was-effectively-final-introduced-in-java-8