Created
July 7, 2017 14:30
-
-
Save danbills/6eba43516c4168f175bc5143ba72f798 to your computer and use it in GitHub Desktop.
enumeratum decoder
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
import enumeratum._ | |
import io.circe.Printer | |
import io.circe.parser._ | |
import io.circe.syntax._ | |
import org.scalatest.prop.TableDrivenPropertyChecks | |
import org.scalatest.{EitherValues, FlatSpec, Matchers} | |
import scala.collection.immutable.IndexedSeq | |
object foo { | |
// Caches for enum encoders and decoders. | |
private val enumEncoderCache = new CompanionCache | |
private val enumDecoderCache = new CompanionCache | |
/** | |
* Provides an encoder for any class that extends EnumEntry. | |
* | |
* Using java reflection it retrieves the EnumEntry's companion, and builds a circe encoder using the library | |
* enumeratum-circe. The encoder is then cached using the type T. | |
* | |
* @tparam T The type of the enum, with a context bound also specifying that an `implicit ctag: ClassTag[T]` exists. | |
* https://www.scala-lang.org/files/archive/spec/2.12/07-implicits.html#context-bounds-and-view-bounds | |
* @return The enum encoder. | |
*/ | |
implicit def encodeEnum[T <: EnumEntry: ClassTag]: Encoder[T] = { | |
enumEncoderCache.cached[T, Enum[T], Encoder[T]](Circe.encoder) | |
} | |
/** | |
* Provides a decoder for any class that extends EnumEntry. | |
* | |
* Using java reflection it retrieves the EnumEntry's companion, and builds a circe decoder using the library | |
* enumeratum-circe. The decoder is then cached using the type T. | |
* | |
* @tparam T The type of the enum, with a context bound also specifying that an `implicit ctag: ClassTag[T]` exists. | |
* https://www.scala-lang.org/files/archive/spec/2.12/07-implicits.html#context-bounds-and-view-bounds | |
* @return The enum decoder. | |
*/ | |
implicit def decodeEnum[T <: EnumEntry: ClassTag]: Decoder[T] = { | |
enumDecoderCache.cached[T, Enum[T], Decoder[T]](Circe.decoder) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment