Recently I've found a subtle difference between anonymous class and lambda expression:
public class FinalTest {
final Runnable x = new Runnable() {
@Override
public void run() {
System.out.println(x.hashCode());
}
};
final Runnable y = () -> System.out.println(y.hashCode());
}
Usually lambdas are equivalent to the anonymous classes. Even my Eclipse IDE has the refactoring to convert the x
to lambda (it becomes exactly like y
) and convert y
to anonymous class (it becomes exactly like x
). However the lambda gives me a compilation error while anonymous class can be perfectly compiled. The error message looks like this:
>javac FinalTest.java
FinalTest.java:9: error: self-reference in initializer
final Runnable y = () -> System.out.println(y.hashCode());
^
1 error
So the question is: why there's such difference?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…