Use a class field in a lambda

Viewed 3870

I don't understand this behavior.

This piece of code complies:

public class A {

    private String s;

    private Function<String, String> f = e -> s;

    public A(String s) {
        this.s = s;
    }
}

But if I make s final, then I get a compiler error:

public class A {

    private final String s;

    private Function<String, String> f = e -> s; // Variable 's' might not have been initialized

    public A(String s) {
        this.s = s;
    }
}

Why is that? If it were the other way around, I'd understand, but how is that the compiler complains when I declare a field final (which forces me to initialize its value in the constructor), and it's OK for it when it's not final?

3 Answers
Related