问题描述
我在 Java 8 中使用 lambdas 并遇到警告从 lambda 表达式引用的局部变量必须是最终的或有效的最终
.我知道当我在匿名类中使用变量时,它们在外部类中必须是 final,但是 - final 和 effectively final 之间有什么区别?
I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final
. I know that when I use variables inside anonymous class they must be final in outer class, but still - what is the difference between final and effectively final?
推荐答案
例如,假设变量 numberLength
未声明为 final,并且您在 PhoneNumber
构造函数中添加了标记的赋值语句:
For example, suppose that the variable numberLength
is not declared final, and you add the marked assignment statement in the PhoneNumber
constructor:
public class OutterClass {
int numberLength; // <== not *final*
class PhoneNumber {
PhoneNumber(String phoneNumber) {
numberLength = 7; // <== assignment to numberLength
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
...
}
...
}
由于这个赋值语句,变量 numberLength 不再有效.因此,Java 编译器会生成类似于从内部类引用的局部变量必须是最终的或有效的最终变量"的错误消息,其中内部类 PhoneNumber 尝试访问 numberLength 变量:
Because of this assignment statement, the variable numberLength is not effectively final anymore. As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final" where the inner class PhoneNumber tries to access the numberLength variable:
http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html
http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
这篇关于最终和有效最终之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!