gpt4 book ai didi

json - 使用 Circe 对 AnyVal 类型进行通用派生

转载 作者:行者123 更新时间:2023-12-01 19:17:45 30 4
gpt4 key购买 nike

我想派生值类的编码器实例。使用 semiauto 机制,我无法派生嵌套类。

想象一下下面的案例类结构

{
case class Recipient(email: Recipient.Email, name: Recipient.Name)

object Recipient {
case class Email(value: String) extends AnyVal
case class Name(value: String) extends AnyVal
}
}

在菊石壳中(还添加接收者案例类)

load.ivy("io.circe" %% "circe-core" % "0.6.1")
load.ivy("io.circe" %% "circe-generic" % "0.6.1")

import io.circe._
import io.circe.generic.semiauto._
import io.circe.syntax._

现在为 Email 结果派生解码器,如预期的那样

Recipient.Email("ab@cd.com").asJson(deriveEncoder[Recipient.Email]) 
Json = {
"value" : "ab@cd.com"
}

派生 Encoder[Recipient] 不起作用

deriveDecoder[Recipient]

could not find Lazy implicit value of type
io.circe.generic.decoding.DerivedDecoder[$sess.cmd5.Recipient]

我想做的是派生一个返回包装类型的Encoder[Recipient.Email]。如果我显式导出编解码器,这个小片段就可以工作。

import shapeless.Unwrapped

implicit def encodeAnyVal[W <: AnyVal, U](
implicit unwrapped: Unwrapped.Aux[W, U],
encoderUnwrapped: Encoder[U]): Encoder[W] = {
Encoder.instance[W](v => encoderUnwrapped(unwrapped.unwrap(v)))
}

Recipient.Email("ab@cd.com").asJson(encodeAnyVal[Recipient.Email, String])
res11: Json = "ab@cd.com"

我仍然无法派生Encoder[Recipient]

implicit val emailEncoder: Encoder[Recipient.Email] = encodeAnyVal[Recipient.Email, String] 
implicit val nameEncoder: Encoder[Recipient.Name] = encodeAnyVal[Recipient.Name, String]

deriveDecoder[Recipient]
cmd14.sc:1: could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[$sess.cmd5.Recipient]

有人做过类似的事情吗?

提前致谢,穆基

最佳答案

您应该添加隐式见证实例而不是类型绑定(bind)。最终会得到这样的结果:

implicit def encodeAnyVal[W, U](
implicit ev: W <:< Anyval,
unwrapped: Unwrapped.Aux[W, U],
encoderUnwrapped: Encoder[U]): Encoder[W] = {
Encoder.instance[W](v => encoderUnwrapped(unwrapped.unwrap(v)))
}

关于json - 使用 Circe 对 AnyVal 类型进行通用派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41192333/

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