由於在下面的代碼中,R擴展了Appendable,所以我不應該能夠返回一個Appendable,其中R是預期的嗎?Java有界的通用協方差
/**
* 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;
}
}
如何在接口中定義方法,this代碼不能編譯。 – sanbhat
因此,只需將它轉換爲'return(R)結果;'?好吧,我只是想確保我理解這個權利,而且演員陣容是有效的。 如果您的意思是將結果聲明爲R,如在'R result = this;'中那樣會引發一個「不兼容的類型:Required R,找到PluralAppendable,這是有意義的,因爲PluralAppendable不擴展R, –
接口中的「default」修飾符和方法體在Java 8中可用,我正在使用 –