0

我想扩展:

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)

不工作。

我认为缺少明显的东西?

4

2 回答 2

3

好吧,你显然不能这样做,因为和Map[A, B]不是协变的。只是尝试一下就会给你一个详细的编译错误:AB

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
于 2012-06-27T17:48:14.077 回答
0

稍微扩展@oxbow_lakes 的答案。“非协变”意味着它Map[String, String]不是 的子类型Map[Any, Any]。你可以看到为什么它不是:

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

但如果response它实际上是一个实例ResponseForJerkson并且errors有 type Map[String, String],这将是非法的。所以有些操作Response是非法的ResponseForJerkson,因此它不能扩展Response

于 2012-06-27T22:41:13.487 回答