Java Reference
In-Depth Information
The
toBinaryString()
method represents a function that takes an
int
as an argument and returns a
String
.
You can use it in a lambda expression as shown:
// Using a lambda expression
Function<Integer, String> func1 = x ->
Integer.toBinaryString(x);
System.out.println(func1.apply(17));
10001
The compiler infers the type of
x
as
Integer
and the return type of the lambda expression as
String
, by using the
target type
Function<Integer, String>
. You can rewrite this statement using a static method reference, as shown:
// Using a method reference
Function<Integer, String> func2 =
Integer::toBinaryString
;
System.out.println(func2.apply(17));
10001
The compiler finds a static method reference to the
toBinaryString()
method of the
Integer
class on the
right-hand side of the assignment operator. The
toBinaryString()
method takes an
int
as an argument and returns
a
String
. The target type of the method reference is a function that takes an
Integer
as an argument and returns a
String
. The compiler verifies that after unboxing the
Integer
argument type of the target type to
int
, the method
reference and target type are assignment compatible.
Consider another static method
sum()
in the
Integer
class:
static int sum(int a, int b)
The method reference would be
Integer::sum
. Let's use it in the same way you used the
toBinaryString()
method in the above example.
Function<Integer, Integer> func2 = Integer::sum; // A compile-time error
The compiler generates the following error message when you compile this code:
Error: incompatible types: invalid method reference
Function<Integer, Integer> func2 = Integer::sum;
method sum in class Integer cannot be applied to given types
required: int,int
found: Integer
reason: actual and formal argument lists differ in length
The error message is stating that the method reference
Integer::sum
is not assignment compatible with the
target type
Function<Integer, Integer>
. The
sum(int, int)
method takes two
int
arguments whereas the target
type takes only one
Integer
argument. The mismatch in the number of arguments caused the compile-time error.