6

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?

Naman
  • 27,789
  • 26
  • 218
  • 353
HPH
  • 388
  • 2
  • 11

1 Answers1

11

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875