I'm trying to rewrite this code
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println(e.hashCode());
}
};
as
new EventHandler<MouseEvent>(e -> System.out.println(e.hashCode()));
and I get errors. What is my mistake here?
The lambda expression is here to replace the whole FunctionalInterface
and not only its method, so it's not constructor + lambda
but only lambda
:
Use the EventHandler
as parameter :
someNode.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println(event.hashCode());
}
});
Becomes :
someNode.addEventHandler(MouseEvent.MOUSE_CLICKED,
event -> System.out.println(event.hashCode()));
Use the EventHandler
in a variable :
EventHandler<MouseEvent> eh = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println(event.hashCode());
}
};
It'll become :
EventHandler<MouseEvent> eh = e -> System.out.println(e.hashCode());
It's exists various way to use lambda, with or without parameter, like :
Runnable r = () -> System.out.println("Here");