Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntFunction<String> and Function<Integer, String>

I have following two simple code:

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

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

like image 650
Tom Avatar asked Oct 24 '17 07:10

Tom


People also ask

Is an integer a string?

Integer is a numeric value, while String is a character value represented in quotes.

What is int function in Java?

Interface IntFunction<R> Represents a function that accepts an int-valued argument and produces a result. This is the int -consuming primitive specialization for Function . This is a functional interface whose functional method is apply(int) .

Can we take integers in a string?

Method 1: Using toString Method of Integer Class The Integer class has a static method that returns a String object representing the specified int parameter. The argument is converted and returned as a string instance. If the number is negative, the sign will be preserved.

How do I convert a string to an int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.


1 Answers

The second method reference is ambiguous:

both the static method

public static String toString(int i)

and the instance method

public String toString()

are applicable.

If you write the second assignment using lambda expressions, you can see there are two methods 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 can't decide which method you are referring to.

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

like image 178
Eran Avatar answered Oct 26 '22 17:10

Eran