【问题标题】:why Buffer[String] can not inherit from Buffer[AnyRef] [duplicate]为什么 Buffer[String] 不能从 Buffer[AnyRef] 继承 [重复]
【发布时间】:2013-06-15 18:59:39
【问题描述】:
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)

【问题讨论】:

    标签: scala


    【解决方案1】:

    简答:您不能将AnyRef 添加到Buffer[String]

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 2019-05-10
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2016-09-06
      相关资源
      最近更新 更多