Skip to content

Commit

Permalink
Add examples for Circe
Browse files Browse the repository at this point in the history
  • Loading branch information
lloydmeta committed Dec 16, 2016
1 parent e9e975c commit 4189bc1
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
29 changes: 29 additions & 0 deletions enumeratum-circe/src/main/scala/enumeratum/CirceEnum.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,35 @@ import io.circe.{Decoder, Encoder}
*/
/**
* Helper trait that adds implicit Circe encoders and decoders for an [[Enum]]'s members
*
* Example:
*
* {{{
* scala> import enumeratum._
* scala> import cats.syntax.either._
* scala> import io.circe._
* scala> import io.circe.syntax._
*
* scala> sealed trait ShirtSize extends EnumEntry
* scala> case object ShirtSize extends Enum[ShirtSize] with CirceEnum[ShirtSize] {
* | case object Small extends ShirtSize
* | case object Medium extends ShirtSize
* | case object Large extends ShirtSize
* | val values = findValues
* | }
*
* scala> val size: ShirtSize = ShirtSize.Small
*
* scala> size.asJson
* res0: Json = "Small"
*
* scala> Json.fromString("Large").as[ShirtSize]
* res1: Decoder.Result[ShirtSize] = Right(Large)
*
*
* scala> Json.fromString("XLarge").as[ShirtSize]
* res2: Decoder.Result[ShirtSize] = Left(DecodingFailure(XLarge' is not a member of enum ShirtSize, List()))
* }}}
*/
trait CirceEnum[A <: EnumEntry] { this: Enum[A] =>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,32 @@ sealed trait CirceValueEnum[ValueType, EntryType <: ValueEnumEntry[ValueType]] {

/**
* CirceEnum for IntEnumEntry
*
* {{{
* scala> import enumeratum.values._
* scala> import cats.syntax.either._
* scala> import io.circe._
* scala> import io.circe.syntax._
*
* scala> sealed abstract class ShirtSize(val value:Int) extends IntEnumEntry
* scala> case object ShirtSize extends IntEnum[ShirtSize] with IntCirceEnum[ShirtSize] {
* | case object Small extends ShirtSize(1)
* | case object Medium extends ShirtSize(2)
* | case object Large extends ShirtSize(3)
* | val values = findValues
* | }
*
* scala> val size: ShirtSize = ShirtSize.Small
*
* scala> size.asJson
* res0: Json = 1
*
* scala> Json.fromInt(3).as[ShirtSize]
* res1: Decoder.Result[ShirtSize] = Right(Large)
*
* scala> Json.fromInt(10).as[ShirtSize]
* res2: Decoder.Result[ShirtSize] = Left(DecodingFailure(10 is not a member of enum ShirtSize, List()))
* }}}
*/
trait IntCirceEnum[EntryType <: IntEnumEntry] extends CirceValueEnum[Int, EntryType] {
this: ValueEnum[Int, EntryType] =>
Expand Down

0 comments on commit 4189bc1

Please sign in to comment.