由于在以下代码中,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;
    }
}

最佳答案

由于在以下代码中,R扩展了Appendable,所以我不应该在期望R的地方返回Appendable吗?


不,你不能。如果继承是相反的,则只能执行此操作。

但是,您可以将result向下转换为R,以进行编译,但是会显示未选中Cast的警告。

return (R)result;

07-24 13:51