gpt4 book ai didi

java - Java8 中不合逻辑的类型推断

转载 作者:行者123 更新时间:2023-11-29 10:14:17 25 4
gpt4 key购买 nike

我想知道为什么☆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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com