0

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?

malibu
  • 77
  • 3
  • 7
  • 1
    The local variable is on the stack, so there's no way of guaranteeing it will stay around for the lifetime of the lambda. – tgdavies Sep 17 '20 at 04:27
  • First example won't compile since static method don't have access to non-static class field. – Slava Medvediev Sep 17 '20 at 04:30
  • @MedvedievV. My bad, I have made the necessary edits. Now does it look correct? – malibu Sep 17 '20 at 04:33
  • @tgdavies But the lambda will live as long as the test method lives, right? Can you give an example where the lambda function could be executed even though we have exited from the test method? – malibu Sep 17 '20 at 04:37

1 Answers1

5

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

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • If `this` is final, then how can I change instance variables using, for example, `this.x = y` – malibu Sep 17 '20 at 04:49
  • 2
    @malibu `this.x = y` is changing the value of field `x`, it is not changing the value of the `this` reference variable. – Andreas Sep 17 '20 at 04:52
  • That makes sense. Also, can you explain why we have the restriction of making variable final for second example? @tgdavies explained "there's no way of guaranteeing it will stay around for the lifetime of the lambda", but I didn't get when would that be possible. – malibu Sep 17 '20 at 05:21
  • 2
    @malibu See [this answer](https://stackoverflow.com/a/61075832/5221149). – Andreas Sep 17 '20 at 05:33