简体   繁体   中英

Java bounded generic covariance

Since in the following code, R extends Appendable, shouldn't I be able to return an Appendable where an R is expected?

/**
  * 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;
    }
}

Since in the following code, R extends Appendable, shouldn't I be able to return an Appendable where an R is expected?

No, you can't. You can only do this, if the inheritance was the other way round.

However, you can downcast result to R , to make it compile, but it will show you warning of Unchecked Cast .

return (R)result;

The opposite can be done. You can return a subclass when you should return a reference of a superclass. In your example you try to do it inversely and of course you need a reference for an Object of type R. You cannot pass an Object of its superclass to a reference of R.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM