我想知道为什么☆2
代码可以用Java8
编译:
public class Sandbox {
public static void main(String[] args) {
// ☆1: NG: Type mismatch: cannot convert from Object to String
String res0 = IList.nil().head();
// ☆2: OK: I don't know why it's OK.
String res1 = IList.nil().head2();
}
static class IList<E> {
static <Z> IList<Z> nil() {
return null;
}
E head() {
return null;
}
<TeE extends E> TeE head2() {
return null;
}
}
}
注意: 我也想知道 JEP( http://openjdk.java.net/jeps/101 ) 的目标。
最佳答案
Java 通常将泛型默认为其外部边界。在这种特殊情况下,它的类型为
String res1 = IList.<Object>nil().<String>head2();
...因为只有最外层的方法调用“知道”所需的结果类型。
关于java - Java8 中不合逻辑的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490835/