In the original question the code
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
is problematic because the object have been registered in the constructor and then may be used by the event managing system while not being fully constructed. In fact, this is dangerous only if doSomething
access something external to the ThisEscape
instance.
And this is the same with your lambda "equivalent"
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(e -> doSomething(e));
}
}
But don't be fooled, anonymous inner classes are not strictly equivalent to lambdas... this
refers to the current instance in case of anonymous inner class but refers to the enclosing instance of the lambda (this
is in the closure of the lambda) :
interface doable {
public void doIt();
}
public class Outer {
public Outer() {
doable d1 = new doable() {
public void doIt() {
System.out.println(this);
}
};
d1.doIt();
doable d2 = ()->System.out.println(this);
d2.doIt();
}
public static void main(String []argv) {
new Outer();
}
}
produces something like :
Outer$1@3764951d
Outer@3cd1a2f1
The second line clearly shows that a lambda is not an instance of any class, it is not an object.