Skip to content

Instantly share code, notes, and snippets.

@ricsirigu
Created June 3, 2017 08:27
Show Gist options
  • Save ricsirigu/3bea41f1ccb3e7447a880aac1bcf0828 to your computer and use it in GitHub Desktop.
Save ricsirigu/3bea41f1ccb3e7447a880aac1bcf0828 to your computer and use it in GitHub Desktop.
Type Class with Type Enrichment
// Type Class example with Type Enrichment
case class Picture(name: String, uri: String)
case class Attachment(name: String, uri: String, visible: Boolean)
trait JsonWriter[T]{
def toJson(in: T): String
}
implicit class JsonSerializer[T](data: T){
def toJson(implicit writer: JsonWriter[T]): String =
writer.toJson(data)
}
implicit object attachmentJsonSerializer extends JsonWriter[Attachment]{
override def toJson(in: Attachment): String = s"attachment ${in.name}"
}
implicit object pictureJsonSerializer extends JsonWriter[Picture]{
override def toJson(in: Picture): String = s"picture ${in.name}"
}
println(new Picture("mypic", "mypicurl").toJson)
println(new Attachment("myattachment", "myurl", false).toJson)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment