变量在Java中的Lambda表达式中的引用

huangapple go评论79阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2020年9月17日 12:25:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63931257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定