Skip to content

Instantly share code, notes, and snippets.

@benkolera
Last active December 29, 2015 23:29
Show Gist options
  • Save benkolera/7743591 to your computer and use it in GitHub Desktop.
Save benkolera/7743591 to your computer and use it in GitHub Desktop.
This can't be the right way to go about this...
import scalaz._
import std.option._
import argonaut._,Argonaut._
object JsonDb {
sealed trait SumType
case class Option1( foo:String ) extends SumType
case class Option2( bar:Int ) extends SumType
private implicit val option1Codec = casecodec1( Option1.apply , Option1.unapply _ )("foo")
private implicit val option2Codec = casecodec1( Option2.apply , Option2.unapply _ )("bar")
implicit def sumTypeCodec = codec2[Option[Option1],Option[Option2],SumType](
(fooOpt,barOpt) => (fooOpt,barOpt) match {
case (Some(o1),_) => o1
case (_,Some(o2)) => o2
case _ => throw new RuntimeException(":(")
},
(sumType) => sumType match {
case o1:Option1 => (some(o1),none[Option2])
case o2:Option2 => (none[Option1],some(o2))
}
)( "option1" , "option2" )
//scala> Option1( "hello world" ).asJson
//res0: argonaut.Json = {"option1":{"foo":"hello world"},"option2":null}
//scala> Option2( 1337 ).asJson
//res1: argonaut.Json = {"option1":null,"option2":{"bar":1337}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment