我写了这段代码
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))
}
这可以正常工作,并且可以编译。但是如果我将“产品类型”更改为使用猫非空集。
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]]"
我该怎么做,以便它像为列表一样自动为NonEmptySet生成解码器?
查看circe source code,如果提供Decoder[NonEmptySet[A]]
和Decoder[A]
,则会提供Order[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]
的隐式。