Last active
April 28, 2017 03:28
-
-
Save abhsrivastava/134cf8c2a78b99a91d48ed13dfe0ad8b to your computer and use it in GitHub Desktop.
Getting Rid of Scala Enums and Clean Json Serialization
This file contains hidden or 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
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