Search code examples
javaanonymous-functionfinal

Variable referencing from a lambda expression in 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?


Solution

  • The first example works, because a = true is actually shorthand for this.a = true, and this is always final (so says the Java Specification).