为什么Java无法在重载方法中推断类型?
我有以下代码,为什么Java无法在重载方法中推断类型?,java,generics,lambda,type-inference,overload-resolution,Java,Generics,Lambda,Type Inference,Overload Resolution,我有以下代码,javac无法选择要使用的重载get()方法的版本。为什么不呢 public class x { static <T> T get(Key<T> key, T defaultValue) {throw new UnsupportedOperationException();} static <T> T get(Key<T> key, java.util.function.Supplie
javac
无法选择要使用的重载get()
方法的版本。为什么不呢
public class x {
static <T> T get(Key<T> key, T defaultValue)
{throw new UnsupportedOperationException();}
static <T> T get(Key<T> key,
java.util.function.Supplier<T> defaultValueSupplier)
{throw new UnsupportedOperationException();}
static void test(){
Key<String> k = new Key<>();
String s = get(k, () -> "test");
}
private static class Key<T>{}
}
然后它就起作用了。是什么导致
javac
将代码与两种方法匹配?可重复<代码>字符串s=get(k,(供应商)(->“测试”)有效。还有另一个解决方法:字符串s=x.get(k,()->“测试”)
@Eran这很有趣,我刚刚用Oracle的1.8.0_60和1.8.0_77(我没有1.8.0_66)进行了测试,也没有编译它。也没有1.8.0_141
和OpenJDK11.0.1
-相同的错误消息
% javac -version
javac 1.8.0_202
% javac x.java
x.java:11: error: reference to get is ambiguous
String s = get(k, () -> "test");
^
both method <T#1>get(Key<T#1>,T#1) in x and method <T#2>get(Key<T#2>,Supplier<T#2>) in x match
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>get(Key<T#1>,T#1)
T#2 extends Object declared in method <T#2>get(Key<T#2>,Supplier<T#2>)
x.java:11: error: incompatible types: cannot infer type-variable(s) T
String s = get(k, () -> "test");
^
(argument mismatch; String is not a functional interface)
where T is a type-variable:
T extends Object declared in method <T>get(Key<T>,T)
2 errors
both method <T#1>get(Key<T#1>,T#1) in x and method <T#2>get(Key<T#2>,Supplier<T#2>) in x match
Key<String> k = new Key<>();
Supplier<String> l = () -> "test";
String s = get(k, l);