简体   繁体   中英

How java.util.function.Function can have a method reference of Object class toString method

Function<Integer, String> intToString = Object::toString

above code is example for method reference

Please help me how it works.

As per my understanding method reference should have the same method signature as Functional Interface abstract method( R apply(T) ).

Essentially, you're right. To assign something to a variable declared like

Function<Integer, String> intToString = value;

then value has to be a Function<Integer, String> , something that has a

public String apply(Integer t) { ... }

method.

The tricky thing is that a method reference expression like Object::toString is syntactic sugar for

Function<Integer, String> intToString = new Function<Integer,String>() {
    public String apply(Integer t) { 
        return t.toString();
    }
};

And how does it know the Integer and String type parameters that aren't mentioned in just the expression Object::toString ? That comes from the left-hand side of the assignment. The compiler knows what type of function is expected and creates an appropriate inner, anonymous Function instance from the method reference Object::toString .

Caveat: A method reference Object::toString is only allowed in situations where the compiler can clearly deduce what type is expected, as this expression's type is unclear. Depending on the context (eg left-hand side), the very same Object::toString can as well become a Consumer<Point> instead of a Function<Integer, String> , then implementing a method void accept(Point t) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM