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!
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.
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.
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.
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.
You are mixing a lambda expression with a method reference.
Change
setOnMouseClicked(event -> SomeClass::onClicked);
to
setOnMouseClicked(SomeClass::onClicked);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With