Last active
September 26, 2018 14:16
-
-
Save ShahOdin/8e219777aad8e37891a1febb42c0b7b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object CirceDecoderCombination { | |
sealed trait Base | |
case class StringField(field1: String) extends Base | |
case class IntField(field2: Int) extends Base | |
case class FloatField(field3: Float) extends Base | |
import io.circe.{Decoder, Encoder} | |
import io.circe.generic.auto._ | |
object Base { | |
import io.circe.syntax._ | |
implicit val encoder: Encoder[Base] = Encoder.instance { | |
case c:StringField => c.asJson | |
case c:IntField => c.asJson | |
case c:FloatField => c.asJson | |
} | |
implicit val decoder: Decoder[Base] = { | |
import cats.syntax.functor._ | |
List[Decoder[Base]]( | |
Decoder[StringField].widen, | |
Decoder[IntField].widen, | |
Decoder[FloatField].widen | |
).reduceLeft(_ or _) | |
} | |
} | |
} | |
class CirceDecoderCombinationSepc extends FlatSpec with Matchers { | |
it should "encode and decode a subtype using its aggregate en/decoder" in { | |
import io.circe.syntax._ | |
val value = StringField("1") | |
val jason = value.asInstanceOf[Base].asJson | |
jason.as[Base] shouldBe Right(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment