我现在可以使用以下版本(我仅使用一个枚举值简化了示例):
import io.circe.*
inline def deriveEnumValueDecoder[A](inline prototype: A): Decoder[A] =
Decoder.decodeString.emap: str =>
if str == prototype.toString
then Right(prototype)
else Left(s"Invalid value: $str")
val json = Json.obj("processStatus" -> Json.fromString("OK"))
val jsonEnum = Json.fromString("OK")
println("MyClass: " + json.as[MyClass])
println("MyEnum: " + jsonEnum.as[MyEnum.OK.type])
case class MyClass(processStatus: MyEnum.OK.type)
enum MyEnum:
case OK, NOK
given Decoder[MyClass] = Decoder.derived
given Decoder[MyEnum.OK.type] = deriveEnumValueDecoder(MyEnum.OK)
参见 Scastie:https://scastie.scala-lang.org/pme123/ntclYMfzQK2U6KP1wv9fIw/2
我想知道是否有办法摆脱提供“原型”,所以我可以这样称呼它:
given Decoder[MyEnum.OK.type] = deriveEnumValueDecoder
inline def deriveEnumValueDecoder[A]: Decoder[A] =
Decoder.decodeString.emap: str =>
if str == valueOf[A].toString
then Right(valueOf[A])
else Left(s"Invalid value: $str - expected: ${valueOf[A]}")
given Decoder[MyEnum.OK.type] = deriveEnumValueDecoder