Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method reference assignment compile?

Tags:

java

java-8

I'm struggling to see why the following code compiles:

public class MethodRefs {      public static void main(String[] args) {         Function<MethodRefs, String> f;          f = MethodRefs::getValueStatic;          f = MethodRefs::getValue;     }      public static String getValueStatic(MethodRefs smt) {         return smt.getValue();     }      public String getValue() {         return "4";     }  } 

I can see why the first assignment is valid - getValueStatic obviously matches the specified Function type (it accepts a MethodRefs object and returns a String), but the second one baffles me - the getValue method accepts no arguments, so why is it still valid to assign it to f?

like image 740
codebox Avatar asked Apr 20 '17 15:04

codebox


People also ask

Why do we use method reference?

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.

How does method reference work?

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 a method reference operator?

Method reference is the way in a lambda expression to refer a method without executing it. In the body of a lambda expression, we can able to call another method if they are compatible with a functional interface. The operator "::" can be used to separate the class name from the method name.

How do you reference a static method in Java?

Static Method They are referenced by the class name itself or reference to the Object of that class. public static void geek(String name) { // code to be executed.... } // Must have static modifier in their declaration. // Return type can be int, float, String or user defined data type.


1 Answers

The second one

f = MethodRefs::getValue; 

is the same as

f = (MethodRefs m) -> m.getValue(); 

For non-static methods there is always an implicit argument which is represented as this in the callee.

NOTE: The implementation is slightly different at the byte code level but it does the same thing.

like image 113
Peter Lawrey Avatar answered Oct 09 '22 02:10

Peter Lawrey