Mat*_*t G 2 java generics covariance java-8
由于在下面的代码中,R扩展了Appendable,我不应该能够返回一个可以预期R的Appendable吗?
/**
* Produces an R, to which a T has been semantically appended,
* whatever that may mean for the given type.
*/
interface Appendable <R, T>
{
/**
* Append is not expected to modify this Appendable,
* but rather to return an R which is the result
* of the append.
*/
R append(T t);
}
interface PluralAppendable <R extends Appendable<R, T>, T>
extends Appendable<R, T>
{
default R append(T... els)
{
// Easier to debug than folding in a single statement
Appendable<R, T> result = this;
for(T t : els)
result = result.append(t);
/* Error: Incompatible types.
Required: R
Found: Appendable<R, T> */
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
由于在下面的代码中,R扩展了Appendable,我不应该能够返回一个可以预期R的Appendable吗?
不,你不能.如果继承是相反的,那么你只能这样做.
但是,您可以向下转换result到R,使它编译,但它会告诉你警告未检查的演员.
return (R)result;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |