scala-cats - 与猫和精炼类型一起使用时无法生成 Circe 解码器

标签 scala-cats circe refined

这段代码是我写的

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/

相关文章:

scala - 为什么 circe `or` 函数(显然是一元函数)与需要二元操作的 reduceLeft 一起工作?

scala - 使用相同谓词进行细化时,如何使用 Scala 的 Refined 库确保类型安全

scala - Scala 中的类型细化但不使用细化

scala - 将 circe 与 Http4s 结合使用时用于精炼类型的解码器

scala - 自由 Monad 的条件行为

Scala-Cats 已验证 : value mapN is not a member of ValidatedNel tuple

scala - 猫 : Non tail recursive tailRecM method for Monads

scala - 为什么这个免费 Monad 解释器不能将 String 解析为 Id[A]

json - 如何在scala中使用Circe解码JSON列表/数组

json - 使用 Scala 中的列表解析递归 JSON 结构