Skip to content

Instantly share code, notes, and snippets.

@ricsirigu
Created June 1, 2017 13:40
Show Gist options
  • Save ricsirigu/7fe19bbe8b671b9cb890cf6140f2363e to your computer and use it in GitHub Desktop.
Save ricsirigu/7fe19bbe8b671b9cb890cf6140f2363e to your computer and use it in GitHub Desktop.
A practical example of subtype polymorphism in Scala
trait Jsonable{
def toJson: String
}
case class Picture(name: String, uri: String) extends Jsonable{
override def toJson = s"picture ${name}"
}
case class Attachment(name: String, uri: String, visible: Boolean) extends Jsonable{
override def toJson = s"attachment ${name}"
}
val picture: Jsonable = new Picture("mypic", "mypicurl")
val attachment: Jsonable = new Attachment("myattachment", "myurl", false)
println(picture.toJson)
println(attachment.toJson)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment