gpt4 book ai didi

scala - 序列化案例对象扩展特征

转载 作者:行者123 更新时间:2023-12-02 00:38:43 27 4
gpt4 key购买 nike

给定一个具有 ANDOR 案例对象子类型的 trait Conjunction:

  trait Conjunction
case object AND extends Conjunction
case object OR extends Conjunction

使用 Play 2 JSON,我尝试编写以下Writes[Conjunction]:

  implicit object ConjunctionWrites extends Writes[Conjunction] {
implicit val orWrites: Writes[OR] = Json.writes[OR]
implicit val andWrites: Writes[AND] = Json.writes[AND]

def writes(c: Conjunction) = c match {
case a@AND => Json.toJson(a)(andWrites)
case o@OR => Json.toJson(o)(orWrites)
}
}

但是我收到了一堆 not find: type AND/OR 错误。

如何序列化这些 case 对象

最佳答案

当您创建案例对象时,您将创建具有该名称的值,而不是类型。因此 ANDOR 不作为类型存在。如果要引用 case 对象的类型,请使用 .type,例如AND.type.

但是,Json.writes 宏仅适用于案例类,不适用于案例对象。您必须编写自己的定义:

implicit object ConjunctionWrites extends Writes[Conjunction] {
def writes(c: Conjunction) = c match {
case AND => Json.toJson("AND")
case OR => Json.toJson("OR")
}
}

关于scala - 序列化案例对象扩展特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353368/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com