Referencing an instance method of an arbitrary object of a specific type ... doesn't work with custom classes?

According to the documentation on "method references", one can create:

A reference to an instance method of an arbitrary object of a specific type

Link: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

I wrote the following code:

public class App {

    public static void main(String[] args) {

        Function<String, String> f1 = String::toString;

        Function<String, String> f2 = App::toString; // Compilation error
    }

    public String toString() {
        return "test";
    }
}

      

However, the "method reference" using the "String" class compiles fine, whereas the same "method reference" using my own App class does not compile fine.

Can anyone tell why?

+3


source to share


3 answers


For a class method reference, the first parameter of the function type is the class type, and the second is the return type of the function. Try:



Function<App, String> f2 = App::toString;

      

+2


source


It should be Function<App, String> f2



+1


source


I think what you are looking for Function<App, String> f2

.

0


source







All Articles