Created
June 3, 2017 08:27
-
-
Save ricsirigu/3bea41f1ccb3e7447a880aac1bcf0828 to your computer and use it in GitHub Desktop.
Type Class with Type Enrichment
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
// 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