Decoding a sealed trait in Argonaut based on JSON structure?

夙愿已清 提交于 2019-12-07 13:15:27

This is the best I've been able to come up with. It doesn't have that fundamental feel of elegance that the partial functions do, but it is a good bit more terse and easier to decipher than my first attempt.

val CodecNewId = casecodec2(NewId.apply, NewId.unapply)("prefix", "id")
val CodecRevisedId = casecodec3(RevisedId.apply, RevisedId.unapply)("prefix", "id", "rev")

implicit val CodecId: CodecJson[Id] = CodecJson(
  {
    case id: NewId => CodecNewId(id)
    case id: RevisedId => CodecRevisedId(id)
  },
   (CodecRevisedId ||| CodecNewId.map(a => a: Id))(_))

We're still using the "concrete" codecs for each sub-type. But we've gotten away from the CodecJson.derive call, we don't need to wrap our encode function in an EncodeJson, and we can map our DecodeJson function instead of type-casting so we can go back to using ||| instead of copying it's implementation, which makes the code a lot more readable.

This is definitely a usable solution, if not quite what I'd hoped for.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!