鉴于以下内容:
scala> trait Parent
defined trait Parent
scala> case class Boy(name: String) extends Parent
defined class Boy
scala> case class Girl(id: Int) extends Parent
defined class Girl
我尝试为它们定义一个隐式格式化程序(反序列化和序列化):
scala> object Formats extends DefaultJsonProtocol {
| implicit val format: RootJsonFormat[Parent] = jsonFormat1(Boy.apply)
| implicit val girlFormat: RootJsonFormat[Parent] = jsonFormat1(Girl.apply)
| }
但是我遇到了编译时错误:
<console>:22: error: type mismatch;
found : spray.json.RootJsonFormat[Boy]
required: spray.json.RootJsonFormat[Parent]
Note: Boy <: Parent, but trait RootJsonFormat is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
implicit val format: RootJsonFormat[Parent] = jsonFormat1(Boy.apply)
^
<console>:23: error: type mismatch;
found : spray.json.RootJsonFormat[Girl]
required: spray.json.RootJsonFormat[Parent]
Note: Girl <: Parent, but trait RootJsonFormat is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
implicit val girlFormat: RootJsonFormat[Parent] = jsonFormat1(Girl.apply)
^
据我了解这个编译时错误消息,RootJsonFormat
是不变的是它的类型参数。
为什么?