Why does this method reference assignment compile?

codebox :

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?

Peter Lawrey :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=424779&siteId=1