为什么Buffer [String]不能从Buffer [AnyRef]继承

时间:2013-06-19 09:39:27

标签: scala

class Test1(buf:Buffer[AnyRef])
class Test2(buf:Buffer[String]) extends Test(buf) 

编译错误:

type mismatch; 
found : scala.collection.mutable.Buffer[String] 
required:  scala.collection.mutable.Buffer[Any] 
Note: org.msgpack.type.Value <: Any, but trait Buffer is invariant in type A. You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)

1 个答案:

答案 0 :(得分:3)

简答:您无法将AnyRef添加到Buffer[String]

val b: Buffer[AnyRef] = Buffer[String]()
b += new Object // ???

Buffer[String]不能为Buffer[AnyRef],因为Buffer[T]在类型参数T上不协变。它不能被声明为协变(Buffer[+T]),因为在逆变位置使用T(例如在+=方法中)。