Consider the following snippet:
public static void main(String[] args) {
Function<String, String> function = String::toUpperCase; //OK
// Comparator<String> comparator = String::toUpperCase; //Compilation error(makes sense, as String.toUpperCase(Locale locale) & String.toUpperCase() are not compatible)
fun(String::toUpperCase); // java: reference to fun is ambiguous
}
public static void fun(Function<String, String> function) { // String apply(String obj)
System.out.println("Function");
}
public static void fun(Comparator<String> comparator) { // int compare(String s1, String s2)
System.out.println("Comparator");
}
I’m failing to understand the reason behing ambiguity error for method invocation fun(String::toUpperCase)
.
As, both of the overloaded versions of String::toUpperCase
themselves are not compatible with int compare(String s1, String s2)
from the Comparator class, then how come the compiler complains about ambiguity in the first place?
Am I missing something here?
New contributor
Rohan Jaiswal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.