Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lambda method reference not working

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!

like image 775
Mayron Avatar asked Nov 26 '15 12:11

Mayron


People also ask

How do you use method reference instead of lambda?

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.

What is method reference in lambda expression?

Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects. Instance methods of an arbitrary object of a particular type.

What is Java 8 method reference?

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

What are equivalent method reference for the following lambda expression?

If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference. In the first two cases, the method reference is equivalent to lambda expression that supplies the parameters of the method e.g. System.


1 Answers

You are mixing a lambda expression with a method reference.

Change

setOnMouseClicked(event -> SomeClass::onClicked);

to

setOnMouseClicked(SomeClass::onClicked);
like image 193
Eran Avatar answered Nov 15 '22 22:11

Eran