Scala子类无法识别父级中的通用映射?

时间:2015-06-16 17:11:44

标签: scala inheritance

我有一个代码片段,如下所示:

abstract class MultipleOutputWriter {
  protected def writers: collection.mutable.Map[Any, OutputStream]
  def write(basePath: String, value: Any)
  def close = writers.values.foreach(_.close)
}
class LocalMultipleOutputWriter extends MultipleOutputWriter {
  protected val writers = collection.mutable.Map[String, FileOutputStream]()
  def write(key: String, value: Any) = {
    //some implementation
  }
}

但是在编译时会抛出父类和派生类writers之间的类型不匹配。为什么会这样? scala编译器是否不检查map参数是否为子类型?

1 个答案:

答案 0 :(得分:1)

Scala地图在密钥类型中是不变的,因此Map[String, _]Map[Any, _]没有类型关系

Map documentation

  

trait Map[A, +B]

请注意A上没有差异标记,因此它是不变的。

你可以参数化它:

abstract class MultipleOutputWriter[K, V <: OutputStream] {
  protected def writers: collection.mutable.Map[K, V]
  def write(basePath: String, value: Any)
  def close = writers.values.foreach(_.close)
}
class LocalMultipleOutputWriter extends MultipleOutputWriter[String, FileOutputStream] {
  protected val writers = collection.mutable.Map[String, FileOutputStream]()
  def write(key: String, value: Any) = {
    //some implementation
  }
}