我有一个代码片段,如下所示:
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参数是否为子类型?
答案 0 :(得分:1)
Scala地图在密钥类型中是不变的,因此Map[String, _]
与Map[Any, _]
没有类型关系
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
}
}