2015-06-16 29 views
0

我有一个代码段,其看起来如下:Scala子类无法识别父类中的通用映射?

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编译器不检查映射参数是否是子类型?

回答

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 
    } 
} 
+0

我想我标志着它过早地纠正。我尝试了你所说的,它仍然给我以下内容:'类型=> scala.collection.mutable.Map [String,java.io.OutputStream];类的MultipleOutputWriter中的重写方法编写器。 值编写者具有不兼容的类型 protected val writers = collection.mutable.Map [String,FileOutputStream]()' – Sohaib

+0

您可能还需要参数化V。更新 – Daenyth