Last active
June 1, 2017 13:40
-
-
Save ricsirigu/c8c2cef6bf0980480ec7aea070675b79 to your computer and use it in GitHub Desktop.
A practical example of the Type class pattern in Scala
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 pattern example in Scala, to achieve ad hoc polymorphism | |
case class Picture(name: String, uri: String) | |
case class Attachment(name: String, uri: String, visible: Boolean) | |
trait JsonSerializer[T]{ | |
def toJson(in: T): String | |
} | |
object JsonSerializer{ | |
def jsonOf[T](in: T)(implicit jsonSerializer: JsonSerializer[T]): String = | |
jsonSerializer.toJson(in) | |
// Or this more succinct version | |
// | |
//def jsonOf[T: JsonSerializer](in: T): String = | |
// implicitly[JsonSerializer[T]].toJson(in) | |
implicit val pictureJsonSerializer = new JsonSerializer[Picture]{ | |
override def toJson(in: Picture): String = s"picture ${in.name}" | |
} | |
implicit val attachmentJsonSerializer = new JsonSerializer[Attachment]{ | |
override def toJson(in: Attachment): String = s"attachment ${in.name}" | |
} | |
} | |
import JsonSerializer._ | |
println(jsonOf(new Picture("mypic", "mypicurl"))) | |
println(jsonOf(new Attachment("myattachment", "myurl", false))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment