Last active
August 29, 2015 13:59
-
-
Save quii/10475916 to your computer and use it in GitHub Desktop.
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
// 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