这段代码是我写的
import io.circe._
import io.circe.refined._
import cats.data._
import cats.implicits._
import eu.timepit.refined.auto._
final case class Translation(lang: LanguageCode, name: ProductName)
final case class Product(id: ProductId, names: List[Translation])
object Translation {
implicit val decode: Decoder[Translation] = Decoder.forProduct2("lang", "name")(Translation.apply)
implicit val encode: Encoder[Translation] = Encoder.forProduct2("lang", "name")(t => (t.lang, t.name))
}
object Product {
implicit val decode: Decoder[Product] = Decoder.forProduct2("id", "names")(Product.apply)
implicit val encode: Encoder[Product] = Encoder.forProduct2("id", "names")(p => (p.id, p.names))
}
这工作正常并且可以编译。但如果我将我的产品类型更改为使用 cats 非空集。
final case class Product(id: ProductId, names: NonEmptySet[Translation])
我收到编译时错误
could not find implicit value for parameter decodeA1:
io.circe.Decoder[cats.data.NonEmptySet[com.abhi.models.Translation]]"
我该怎么做才能像为 List 那样自动生成 NonEmptySet 的解码器?
最佳答案
查看circe source code如果给定一个 Decoder[A]
和一个 Order[A]
,它会提供一个 Decoder[NonEmptySet[A]]
。
implicit final def decodeNonEmptySet[A](implicit decodeA: Decoder[A], orderA: Order[A]): Decoder[NonEmptySet[A]] =
new NonEmptySeqDecoder[A, SortedSet, NonEmptySet[A]](decodeA) {
final protected def createBuilder(): Builder[A, SortedSet[A]] = SortedSet.newBuilder[A](Order.catsKernelOrderingForOrder(orderA))
final protected val create: (A, SortedSet[A]) => NonEmptySet[A] = (h, t) => NonEmptySet(h, t)
}
我的猜测是您缺少 Order[Translation]
的隐式。
关于scala-cats - 与猫和精炼类型一起使用时无法生成 Circe 解码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476443/