Ambiguity and Overload Resolution
You'll learn how the Java compiler resolves confusion when multiple overloaded methods can accept the same lambda expression.
When you pass a lambda expression to a method, the compiler uses target typing to figure out which functional interface you mean. But what happens when a class has multiple overloaded methods that could all accept your lambda? The compiler follows specific rules to resolve this ambiguity.
Understanding the Problem
Imagine you have two overloaded methods:
void process(Predicate<String> pred) { /* ... */ }
void process(Function<String, Boolean> func) { /* ... */ }
Now you write:
process(s -> s.isEmpty());
Both methods could accept this lambda! The Predicate expects a boolean result, and so does Function<String, Boolean>. The compiler must decide which one you meant.
How Java Resolves Ambiguity
The compiler tries these strategies in order:
- Most Specific Method: If one overload is more specific than the others (accepts a narrower type), it wins.
- Explicit Casting: You can cast the lambda to clarify which functional interface you mean:
process((Predicate<String>) s -> s.isEmpty()); - Compilation Error: If ambiguity can't be resolved, the compiler rejects the code with an error message about ambiguous method calls.
Practical Example
void execute(Consumer<String> consumer) { /* ... */ }
void execute(Function<String, String> function) { /* ... */ }
// Ambiguous - both could work
execute(s -> System.out.println(s)); // ERROR: ambiguous
You'd need to cast: execute((Consumer<String>) s -> System.out.println(s));
Key Takeaway: When lambda expressions match multiple overloaded methods, use explicit casts to specify the target functional interface and resolve ambiguity.