如何为 Scala 3 枚举值提供通用的 Circe 解码器?

问题描述 投票:0回答:1
在我的模型中,我有枚举值的子集(使用精炼类型)。所以我需要为这些枚举值提供解码器。

我现在可以使用以下版本(我仅使用一个枚举值简化了示例):

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
    
scala enums decoding scala-3 circe
1个回答
0
投票
Mateusz Kubuszok 的评论:

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
    
© www.soinside.com 2019 - 2024. All rights reserved.