Java限制了通用协方差

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)

Roh*_*ain 5

由于在下面的代码中,R扩展了Appendable,我不应该能够返回一个可以预期R的Appendable吗?

不,你不能.如果继承是相反的,那么你只能这样做.

但是,您可以向下转换resultR,使它编译,但它会告诉你警告未检查的演员.

return (R)result;
Run Code Online (Sandbox Code Playgroud)