Consider the following simple code:
public class Test {
private final int arg;
private final Runnable runnable1 = new Runnable() {
@Override
public void run() {
// No errors here, exactly as expected
System.out.println("ARG: " + arg);
}
};
// Error: variable arg might not have been initialized
private final Runnable runnable2 = () -> System.out.println("ARG: " + arg);
public Test(int arg) {
this.arg = arg;
}
}
The java compiler (version 1.8.0-b132) produces the following error when compiling this code: "Error:(14, 46) java: variable arg might not have been initialized"
Actually, I do not expect the error here.
Both declarations 'runnable1' and 'runnable2' are essentially the same: these are just Runnable objects accessing value of the 'arg' field (which is initialized in the constructor).
The only difference between the declarations is that 'runnable1' - is an old-fashion instantiation of Runnable, whereas 'runnable2' - is an instantiation of Runnable via a lambda expression.
I expect them both to work the same.
Is my expectation wrong, or is this a bug in java compiler?
Any help will be appreciated.