我正在使用play框架,并且有一个抽象类:
abstract class Base{...}
在随播对象中有自己的隐式JSON编写器
object Base {
implicit val baseWrites: Writes[Base] = (...)(unlift(Base.unapply))
}
我将这个抽象类子类化:
case class SubClass{...}
在其伴随对象中也有自己的隐式JSON编写器
object SubClass {
implicit val subClassWrites: Writes[SubClass] = (...)(unlift(SubClass.unapply))
}
当我尝试使用Json.toJson(SubClass)序列化子类对象时,出现错误:
[error] both value subClassWrites in object SubClass of type => play.api.libs.json.
Writes[models.SubClass]
[error] and value baseWrites in object Base of type =>
play.api.libs.json.Writes[models.Base]
[error] match expected type play.api.libs.json.Writes[models.SubClass]
[error] Ok(Json.toJson(SubClass.find(id)))
有什么办法可以消除歧义?
最佳答案
因为Writes
具有变量类型参数A
,您将发生碰撞:
trait Writes[-A] extends AnyRef
这意味着
Writes[Base]
是Writes[SubClass]
的子类-您可以在需要Writes[Base]
的地方使用Writes[SubClass]
。问题在这里:
val base: Base = new SubClass(...)
val jsBase = Json.toJson(base)
因此,
Writes[Base]
应该能够序列化SubClass
的实例。在这种情况下,您可以使用ADT
:sealed trait Base
object Base {
implicit val baseWrites: Writes[Base] =
new Writes[Base]{
def writes(o: Base): JsValue = o match {
case s: SubClass => SubClass.writes.writes(s)
case s: SubClass2 => SubClass2.writes.writes(s)
}
}
}
case class SubClass(...) extends Base
object SubClass {
val writes: Writes[SubClass] = (...)(unlift(SubClass.unapply))
}
case class SubClass2(...) extends Base
object SubClass2 {
val writes: Writes[SubClass2] = (...)(unlift(SubClass2.unapply))
}
使用
sealed
关键字,如果match
不够详尽,则会收到警告。