Skip to content

Instantly share code, notes, and snippets.

@abhsrivastava
Last active April 28, 2017 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhsrivastava/134cf8c2a78b99a91d48ed13dfe0ad8b to your computer and use it in GitHub Desktop.
Save abhsrivastava/134cf8c2a78b99a91d48ed13dfe0ad8b to your computer and use it in GitHub Desktop.
Getting Rid of Scala Enums and Clean Json Serialization
sealed case class Color(value: String)
object Color {
object red extends Color("red")
object green extends Color("green")
object blue extends Color("blue")
}
// pattren matching
val x = Color.red
val y = Color.green
val z = "pink"
Color(z) match {
case Color.red => println("color is red")
case _ => println("unknown color") // prints: unknown color
}
// json serialization without any special case like enums
case class Person(name: String, favColor: Color)
val person = Person("Abhishek", Color.red)
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
val json = person.asJson.noSpaces
println(json) // prints: {"name":"Abhishek","favColor":{"value":"red"}}
val person2 = decode[Person](json)
println(person2) // prints: person2: Either[Error, Person] = Right(Person("Abhishek", Color("red")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment