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
?
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.
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 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.
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.
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.
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