斯卡拉覆盖地图

时间:2012-06-27 17:38:20

标签: scala

我想延伸:

case class Response(request: String, errors: Map[Any, Any])

使用更具体的地图,但是:

case class ResponseForJerkson(override val request: String, override val errors: Map[String, String]) extends Response(request, errors)

无效。

我觉得缺少一些明显的东西?

2 个答案:

答案 0 :(得分:3)

嗯,你显然不能这样做,因为Map[A, B]A中的B不协变。试试这个会给你一个详细的编译错误:

scala> class A(val m: Map[Any, Any])
defined class A

scala> class B(override val m: Map[String, String]) extends A(m)
<console>:8: error: type mismatch;
 found   : Map[String,String]
 required: Map[Any,Any]
Note: String <: Any, but trait Map is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
       class B(override val m: Map[String, String]) extends A(m)
                                                              ^

它适用于协变类型:

scala> class C(val m: List[Any])
defined class C

scala> class D(override val m: List[String]) extends C(m)
defined class D

答案 1 :(得分:0)

延长@oxbow_lakes的答案。 “not covariant”表示Map[String, String]不是Map[Any, Any]的子类型。你可以看出它为什么不是:

def foo(response: Response) = response.errors.get(0) // legal, because 0 is an Any

但如果response实际上是ResponseForJerkson的实例且errors的类型为Map[String, String],那么这将是非法的。因此,Response上的操作对于ResponseForJerkson是非法的,因此无法扩展Response