Java Reference
In-Depth Information
A
BinaryOperator
is special type of
BiFunction
for which the arguments and the return
type are all the same. For example, adding two integers would be a
BinaryOperator
.
Because lambda expressions have the types of their functional interfaces, the same rules ap-
ply when passing them as arguments. We can overload a method with the
BinaryOperator
and an interface that extends it. When calling these methods, Java will infer the type of your
lambda to be the most specific functional interface. For example, the code in
Example 4-7
prints out
IntegerBinaryOperator
when choosing between the two methods in
Example 4-7. Another overloaded method call
overloadedMethod
((
x
,
y
) ->
x
+
y
);
Example 4-8. A choice between two overloaded methods
private
private interface
interface
IntegerBiFunction
IntegerBiFunction
extends
extends
BinaryOperator
<
Integer
> {
}
private
private
void
void
overloadedMethod
(
BinaryOperator
<
Integer
>
lambda
) {
System
.
out
.
print
(
"BinaryOperator"
);
}
private
private
void
void
overloadedMethod
(
IntegerBiFunction lambda
) {
System
.
out
.
print
(
"IntegerBinaryOperator"
);
}
Of course, when there are multiple method overloads, there isn't always a clear “most specif-
ic type.” Take a look at
Example 4-9
.
Example 4-9. A compile failure due to overloaded methods
overloadedMethod
((
x
) ->
true
true
);
private
private interface
interface
IntPredicate
IntPredicate
{
public
public
boolean
boolean
test
(
int
int
value
);
}
private
private
void
void
overloadedMethod
(
Predicate
<
Integer
>
predicate
) {
System
.
out
.
print
(
"Predicate"
);
}
private
private
void
void
overloadedMethod
(
IntPredicate predicate
) {
System
.
out
.
print
(
"IntPredicate"
);
}