Why was 'effectively final' introduced in Java 8? [duplicate]

…衆ロ難τιáo~ 提交于 2021-02-11 17:51:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!