4

这感觉很基本;我很抱歉。

考虑

trait Foo[+T] { def t : T }  
trait Bar[+S,+T] extends Foo[T] { def s : S }  
trait Baz[+S,T] extends Foo[T] { def s : S }

Foo 中 T 的协方差是否自动适用于 Baz,即使 Baz 中的 T 未标记为协变?Bar 和 Baz 的行为之间会有任何有意义的区别吗?

(玩弄一下,这两种形式似乎很难区分。如果它们相同,那么 Baz 形式没有警告或发出错误信号会让人感觉很脏,因为单独看 Baz 你会认为 T 不是变体。)

4

1 回答 1

5

不,Baz[T]不会继承 的协方差Foo[+T]。必须明确标记协方差。这是一个例子,

class Foo[+T] {}
class Baz[T] extends Foo[T] {}

(new Foo[String]) : Foo[Any] // Ok: Foo[+T] is covariant
(new Baz[String]) : Foo[Any] // Ok: Baz[String] <: Foo[String] <: Foo[Any]
(new Baz[String]) : Baz[Any] // Error: Baz[T] is invariant in type T
于 2013-03-06T02:42:19.150 回答