2
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)
4

1 回答 1

3

简短回答:您不能添加AnyRefBuffer[String]

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

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

于 2013-06-19T10:02:04.730 回答