Search code examples
javagenericslambdajava-8functional-interface

Why Java is not complaining about an ambiguous call?


A service interface declares two methods which apparently do the same processing :

interface Service<T> {
    <R> R process(Function<? super T, ? extends R> function);
    T process(UnaryOperator<T> operator);
}

The service above is being called like below :

void process(Service<CharSequence> service) {
    service.process(sequence -> sequence.subSequence(0, 1));
}

Which one of the service methods are going to be called and why the compiler does not complain about an ambiguous call in this context?


Solution

  • Method resolution chooses the most specific matching method when there are multiple possible matches. Since UnaryOperator<T> extends Function<T,T>, if that lambda matches it (and it does), it's more specific than Function<T, T> so the UnaryOperator overload will be used.