相关疑难解决方法(0)

为什么java 8 lambdas允许访问非final类变量?

我理解为什么编译器不接受以下内容:

class Foo {
    public Supplier<String> makeSupplier() {
        String str = "hello";
        Supplier<String> supp = () -> return str;

        // gives the expected compile error because
        // str is not effectively final
        // (str is a local variable, compile-time error
        //  as per JLS 15.27.2.)
        str = "world";

        return supp;
    }
}
Run Code Online (Sandbox Code Playgroud)

令我困惑的是编译器接受以下内容,并且单元测试通过:

class Bar {
    private String str = "hello";

    public void setStr(String str) {
        this.str = str;
    }

    public Supplier<String> makeSupplier() {
        Supplier<String> supp = () -> { …
Run Code Online (Sandbox Code Playgroud)

java lambda java-8

8
推荐指数
1
解决办法
3272
查看次数

标签 统计

java ×1

java-8 ×1

lambda ×1