Java Lambda method reference not working

Mayron picture Mayron · Nov 26, 2015 · Viewed 9k times · Source

My original code is this:

private static void onClicked(MouseEvent event) {
    // code to execute
}

// somewhere else in the program:
setOnMouseClicked(event -> SomeClass.onClicked(event));

But IntelliJ says "Can be replaced with method reference" which I'm not too sure how to do. I thought I would do this:

setOnMouseClicked(event -> SomeClass::onClicked);

But then that tells me "void is not a functional interface", but I don't want to return anything. I just want the handler to execute. How can I fix this?

Thank you!

Answer

Eran picture Eran · Nov 26, 2015

You are mixing a lambda expression with a method reference.

Change

setOnMouseClicked(event -> SomeClass::onClicked);

to

setOnMouseClicked(SomeClass::onClicked);