Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 868
HPH Avatar asked Jan 19 '19 13:01

HPH


People also ask

What is ambiguous method call in Java?

This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.

What is ambiguity problem in Java?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading.

What is ambiguous invocation in Java explain with example?

Ambiguous Invocation. □ Sometimes there may be two or more possible. matches for an invocation of a method, but the. compiler cannot determine the most specific match. This is referred to as ambiguous invocation.

Why do we get error when method call is ambiguous?

The error we get makes perfect sense; the parameter to load () can be assigned to either, so we get an error that states the method call is ambiguous.

What is the ambiguity problem in Java?

This is the ambiguity problem in java. Now, the code is confused which “carModelName” variable to use from which interface and to it is now in a ambiguous situation. And hence if this code runs it will give error like: Hope it helps. If not ask in comment section.

How does Java decide which overloaded method to call?

Case 1: Methods with only Varargs parameters In this case, Java uses the type difference to determine which overloaded method to call. If one method signature is strictly more specific than the other, then Java chooses it without an error. static void fun (float...

What does it mean when a token is ambiguous?

the details very much depend on language and context, but in general, it’s when a token, for example function call, cannot be properly resolved, because it’s ambiguous between two functions. for example, if you have two namespaces, Ns1, and Ns2, and both contain a class named Random.


1 Answers

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.

like image 56
T.J. Crowder Avatar answered Oct 20 '22 12:10

T.J. Crowder