背景:这个问题出现在this answer中(确切地说,是答案的第一个修订版)。这个问题中提供的代码被减少到最低限度来解释这个问题。
假设我们有以下代码:
public class Sample<T extends Sample<T>> {
public static Sample<? extends Sample<?>> get() {
return new Sample<>();
}
public static void main(String... args) {
Sample<? extends Sample<?>> sample = Sample.get();
}
}
它在没有警告的情况下编译,并且执行得很好。然而,如果有人试图以某种方式在get()
中显式地定义return new Sample<>();
的推断类型,编译器就会抱怨。
到目前为止,我的印象是菱形运算符只是一些语法糖,不需要编写显式类型,因此总是可以用一些显式类型替换。对于给定的示例,我无法为返回值定义任何显式类型来编译代码。是否可以显式定义返回值的泛型类型,或者在这种情况下是否需要菱形运算符?
下面是我用相应的编译器错误显式定义返回值的泛型类型的一些尝试。
return new Sample<Sample>
的结果是:
Sample.java:6: error: type argument Sample is not within bounds of type-variable T
return new Sample<Sample>();
^
where T is a type-variable:
T extends Sample<T> declared in class Sample
Sample.java:6: error: incompatible types: Sample<Sample> cannot be converted to Sample<? extends Sample<?>>
return new Sample<Sample>();
^
return new Sample<Sample<?>>
的结果是:
Sample.java:6: error: type argument Sample<?> is not within bounds of type-variable T
return new Sample<Sample<?>>();
^
where T is a type-variable:
T extends Sample<T> declared in class Sample
return new Sample<Sample<>>();
的结果是:
Sample.java:6: error: illegal start of type
return new Sample<Sample<>>();
^
https://stackoverflow.com/questions/50936309
复制相似问题