IntFunction <String> and function <Integer, String>

I have two simple codes:

IntFunction<String> f1 = Integer::toString; Function<Integer, String> f2 = Integer::toString; 

I thought that both definitions are correct and that the same thing is the same thing, but the second one has a compilation of errors, complaining that Required Function<Integer, String>,but Method Reference is found.

+5
source share
1 answer

The second method link is ambiguous:

as a static method

 public static String toString(int i) 

and instance method

 public String toString() 

.

If you write the second task using lambda expressions, you can see that there are two methods that you can use:

 Function<Integer, String> f2 = i -> Integer.toString (i); 

or

 Function<Integer, String> f2 = i -> i.toString (); 

when you assign Integer::toString , the compiler cannot decide which method you are accessing.

In the case of IntFunction<String> , on the other hand, only public static String toString(int i) applicable.

+6
source

Source: https://habr.com/ru/post/1272840/


All Articles