Skip to content

Instantly share code, notes, and snippets.

@quii
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save quii/10475916 to your computer and use it in GitHub Desktop.
Save quii/10475916 to your computer and use it in GitHub Desktop.
// Pretend this is your awesome library code that you want others to use freely
object MyAmazingSerialisationLib{
trait Serialiser[A]{
def toJson(x: A): String
}
def writeJsonToDisk[A](item: A)(implicit serialiser: Serialiser[A]){
def writeToDisk(x: String) {println(s"I saved [$x] to disk, honest!")}
writeToDisk(serialiser.toJson(item))
}
}
object TypeClasses extends App {
import MyAmazingSerialisationLib._
case class Dog(name: String)
case class ComputerMachine(id: Int, complexity: Int)
implicit val dogSerialiser = new Serialiser[Dog] {
def toJson(dog: Dog) = s"""{"name":"${dog.name}"}"""
}
// compiles because we have evidence of serialiser
writeJsonToDisk(Dog("Spot"))
// doesn't compile because we dont have a serialiser in scope
writeJsonToDisk(ComputerMachine(2, 20))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment