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)
答案 0 :(得分:3)
简答:您无法将AnyRef
添加到Buffer[String]
:
val b: Buffer[AnyRef] = Buffer[String]()
b += new Object // ???
Buffer[String]
不能为Buffer[AnyRef]
,因为Buffer[T]
在类型参数T
上不协变。它不能被声明为协变(Buffer[+T]
),因为在逆变位置使用T
(例如在+=
方法中)。