能够在Java 8 lambda表达式中有效使用final变量的好处是什么? [英] 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.
我不明白为什么lambda表达式/烦人的内部类需要使用有效的最终变量?为什么Java 8会放松对变量必须声明为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?
是否只是在变量之前保存 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?
推荐答案
简单的答案是,因为没有 final
与有效最终变量之间的差异,除了声明中的关键字 final
之外,唯一的目的是允许省略 final
关键字。
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.
对于lambda表达式,参数的整个声明可以简化为 x - > X + 1
。现在考虑嵌套的lambda表达式,如: x - > y - > x + y
以及如果我们强制将 final
声明添加到 x <将会创建的视觉混乱/ code>参数在这里。
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.
由于没有Java语法可以将变量声明为 final
指定它的类型它要么要求规范在语言中添加更复杂的构造,要么强制我们在参数中添加 final
和类型声明来转换简单表达式 x - > y - > x + y
进入(最终双x) - > y - > x + y
。
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
.
主要目标是为Java程序员提供简化(就此而言)可以在添加新的编程语言功能时使用)。当然,它没有提供语言的任何功能来解决在没有它之前无法解决的问题(这适用于整个lambda特征),但表现力有明显的好处,不仅因为你可以省略 final
修饰符但它有帮助。它与一起与改进的类型推断,新的编程API,当然还有lambda表达式和方法引用一起工作。
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.
这篇关于能够在Java 8 lambda表达式中有效使用final变量的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!