英文:
Variable referencing from a lambda expression in Java
问题
以下是您提供的翻译内容:
为什么 Java 允许这样,
class Test {
boolean a;
public void test() {
...
object.method(e -> a = true);
}
}
但不允许这样,
class Test {
public void test() {
boolean a;
...
object.method(e -> a = true);
}
}
对于第二个示例,它会抛出:
local variables referenced from a lambda expression must be final or effectively final
第二个示例的唯一区别是变量是在方法内部声明的,而不是在类本身声明的。作为 Java 编程的初学者,我是否漏掉了一些明显的内容?
英文:
Why does Java allow this,
class Test {
boolean a;
public void test() {
...
object.method(e -> a = true);
}
}
But not this,
class Test {
public void test() {
boolean a;
...
object.method(e -> a = true);
}
}
For the second example, it throws:
local variables referenced from a lambda expression must be final or effectively final
The only difference in second example is that the variable is declared inside the method instead of the class itself. I am a beginner in Java programming, am I missing something obvious?
答案1
得分: 5
第一个示例有效,因为a = true
实际上是this.a = true
的速记,而且this
始终是final
(正如Java规范所述)。
英文:
The first example works, because a = true
is actually shorthand for this.a = true
, and this
is always final
(so says the Java Specification).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论