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.
Integer is a numeric value, while String is a character value represented in quotes.
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) .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With