我在 Java 8 中使用 lambda,我遇到了警告从 lambda 表达式引用的局部变量必须是最终的或有效的最终
。我知道当我在匿名类中使用变量时,它们在外部类中必须是最终的,但是 - final 和 有效地最终 之间有什么区别?
最佳答案
... starting in Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.
例如,假设变量 numberLength
没有声明为 final,而你在 PhoneNumber
构造函数中添加了标记的赋值语句:
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 不再是有效的 final。 因此,Java 编译器会生成类似于“从内部类引用的局部变量必须是最终或有效最终”的错误消息,其中内部类 PhoneNumber 尝试访问 numberLength 变量:
http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html
http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
关于java - 最终和有效最终之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938095/