Sub topic 15
When Lambdas Make Overloads Ambiguous
An overloaded method is a method name with more than one version, where each version has different parameter types. Java picks a version by looking at the arguments you pass. Most of the time this works without you noticing. With lambdas, it can fail, and you get a compile error that seems strange at first.
This chapter explains why the compiler sometimes cannot choose between overloads when you pass a lambda, how it decides when it can, and the simple fixes you can use.
Why This Happens
In earlier chapters you saw that a lambda has no type of its own. Its type comes from the place where you use it. That type is called the target type. If you assign a lambda to a Function<String, Integer> variable, the compiler knows the lambda is a Function.
A method call with overloads gives the compiler more than one possible target type. The compiler has to pick an overload before it knows the lambda's type, and it needs the lambda's type to pick the overload. When a lambda's parameters have no written types, the compiler often cannot settle this. It reports the call as ambiguous, which means it found more than one good match and could not tell which one you meant.
A Call That Will Not Compile
The two methods below share a name. One accepts a Function<String, Integer>. The other accepts a ToIntFunction<String>, the primitive version you met in the chapter on boxing. Both describe "take a String, give back a number."
import java.util.function.Function;
import java.util.function.ToIntFunction;
public class AmbiguousDemo {
static void measure(Function<String, Integer> f) {
System.out.println("Function: " + f.apply("lambda"));
}
static void measure(ToIntFunction<String> f) {
System.out.println("ToIntFunction: " + f.applyAsInt("lambda"));
}
public static void main(String[] args) {
// Uncommenting the next line causes a compile error:
// "reference to measure is ambiguous"
// measure(s -> s.length());
// Fix 1: cast the lambda to the interface you want
measure((ToIntFunction<String>) s -> s.length()); // ToIntFunction: 6
// Fix 2: store the lambda in a typed variable first
Function<String, Integer> len = s -> s.length();
measure(len); // Function: 6
}
}The lambda s -> s.length() fits both interfaces. s.length() returns an int. That works for ToIntFunction, and Java can box it to an Integer for Function. The parameter s has no written type, so the compiler does not look closely at the lambda's body when it ranks the overloads. Neither overload wins, and the call fails.
How the Compiler Chooses
The compiler picks an overload in two steps.
- Applicability. It finds every overload that could accept the arguments. For a lambda, it checks that the interface's single abstract method has the right number of parameters. It also checks whether the method returns a value or returns nothing (
void). That second check is called the lambda's shape. - Most specific. If more than one overload is applicable, it tries to pick the best one. For lambdas, this step only uses detailed rules when the lambda is explicitly typed, which means every parameter has a written type. A lambda with zero parameters counts as explicitly typed, because it has no parameters left to infer.
If step 2 cannot pick one overload, you get the ambiguity error.
Shape Often Settles It: Runnable vs Supplier
Sometimes the shape of a lambda is enough to rule out an overload, so no ambiguity ever arises. Runnable.run() returns nothing. Supplier.get() returns a value. Look at how the compiler handles different lambda bodies:
import java.util.function.Supplier;
public class ShapeDemo {
static void run(Runnable r) {
System.out.println("Runnable chosen");
r.run();
}
static void run(Supplier<String> s) {
System.out.println("Supplier chosen: " + s.get());
}
public static void main(String[] args) {
// println returns void, so only Runnable fits
run(() -> System.out.println("printing"));
// A plain value is not a statement, so only Supplier fits
run(() -> "a value");
// A block with no return statement fits only Runnable
run(() -> { "abc".toUpperCase(); });
// A method call that returns a value fits BOTH.
// The lambda has zero parameters, so the compiler compares
// return types and prefers the one that returns something.
run(() -> "abc".toUpperCase());
}
}Output:
Runnable chosen
printing
Supplier chosen: a value
Runnable chosen
Supplier chosen: ABCThe last call is the interesting one. "abc".toUpperCase() can be used as a statement, where the result is thrown away, or as a value. So both overloads are applicable. Because the lambda has no parameters, step 2 applies its detailed rules, and an overload that returns a value counts as more specific than one that returns void. The real Java library behaves the same way: ExecutorService.submit(() -> compute()) picks the Callable version over the Runnable one.
Method References Can Be Ambiguous Too
A method reference can also cause trouble when the method it names is itself overloaded. Integer has a static toString(int) and an instance toString(). Both can act as a Function<Integer, String>:
import java.util.function.Function;
public class MethodRefAmbiguity {
public static void main(String[] args) {
// Uncommenting the next line causes a compile error,
// because Integer::toString could mean either toString method.
// Function<Integer, String> bad = Integer::toString;
// Fix: write a lambda that names exactly one method
Function<Integer, String> good = i -> Integer.toString(i);
System.out.println(good.apply(42) + "!"); // 42!
}
}When a method reference will not compile, change it back into a lambda. The lambda states which method you mean.
Fixes at a Glance
| Fix | Example | When to use it |
|---|---|---|
| Cast the lambda | `measure((ToIntFunction<String>) s -> s.length())` | Quick fix at one call site |
| Assign to a typed variable | `Function<String, Integer> len = s -> s.length();` | The lambda is reused or long |
| Change the body's shape | `() -> { compute(); }` | Choosing between void and value-returning versions |
| Replace a method reference with a lambda | `i -> Integer.toString(i)` | The referenced method is overloaded |
| Give overloads different names | `comparingInt`, `mapToInt` | You are designing the API yourself |
Designing APIs That Avoid the Problem
The Java library designers ran into this problem themselves. That is why Comparator has comparing, comparingInt, comparingLong, and comparingDouble as separate names instead of one overloaded comparing. Streams have map and mapToInt for the same reason. If comparingInt were just another comparing overload, then Comparator.comparing(s -> s.length()) would be ambiguous in the same way as measure above.
When you write your own methods, follow the same rule. Do not overload a method name where the same parameter position takes different functional interfaces with the same number of parameters. Use a different name for each version. Callers can then pass any lambda and never need a cast.
Summary
- A lambda gets its type from its target. Overloads give it several possible targets.
- The compiler first keeps the overloads whose interface fits the lambda's parameter count and its void or value shape.
- If several remain and the lambda's parameters have no written types, the call is usually ambiguous.
- Fix it with a cast, a typed variable, a different body shape, or a lambda in place of a method reference.
- In your own APIs, give the versions different names instead of overloading them.
Exercise
Given overloads void handle(Predicate<String> p) and void handle(Function<String, Boolean> f), does handle(s -> s.isEmpty()) compile? If not, give a one-line fix that calls the Predicate version.
Show answer
It does not compile. Both interfaces take one String and return a boolean value, and the lambda's parameter has no written type, so the compiler reports that the reference to handle is ambiguous. One fix is handle((Predicate<String>) s -> s.isEmpty());.
Exercise
With overloads run(Runnable r) and run(Supplier<String> s), which version does each call pick: (a) run(() -> "hi"), (b) run(() -> { System.out.println("hi"); }), (c) run(() -> "hi".trim())?
Show answer
(a) Supplier, because a bare value cannot be a statement, so only Supplier fits. (b) Runnable, because a block with no return statement fits only a void method. (c) Supplier. The call "hi".trim() fits both shapes, but the lambda has zero parameters, so the compiler compares return types and prefers the overload that returns a value.
Exercise
You are designing a class with static int total(List<String> items, ToIntFunction<String> f) and want to add a version that accepts ToDoubleFunction<String>. How should you name it, and why?
Show answer
Give it a different name, such as totalAsDouble, instead of overloading total. Both interfaces take one parameter, so a call like total(items, s -> s.length()) would match both overloads and fail as ambiguous. The Java library uses the same approach with comparingInt and comparingDouble.