Using Java 8, I get a compiler error for the following code:
public class Ambiguous {
public static void call() {
SomeDataClass data = new SomeDataClass();
callee(data, SomeDataClass::getString);
// compiler errors:
// 1. at callee method name:
// The method callee(SomeDataClass, Function<SomeDataClass,String>) is ambiguous for the type Ambiguous
// 2. at lambda:
// Type mismatch: cannot convert from boolean to String
callee(data, d -> d.getRandom() > 0.5);
}
public static void callee(SomeDataClass data, Function<SomeDataClass, String> extractString) {
System.out.println(extractString.apply(data));
}
public static void callee(SomeDataClass data, Predicate<SomeDataClass> check) {
System.out.println(check.test(data));
}
}
// token data class
final class SomeDataClass {
public String getString() {
return "string";
}
public final double getRandom() {
return Math.random();
}
}
So essentially the compiler says "I know you return boolean but you shouldn't, and if you don't I'm not sure what method to use" instead of "oh you're returning boolean, you must mean the Predicate version of the method"? How does this confusion get created?
I'd understand if Predicate<T> extends Function<T, Boolean> (so they have a common Type) but that's not the case.
I do know how to fix it; it's fine if I do
callee(data, (Predicate<SomeDataClass>) d -> d.getRandom() > 0.5);
but I'm curious what causes it.