-
-
Save Softsapiens/10922781 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
trait Serialiser[A]{ | |
def toJson(x: A): String | |
} | |
// [A: Serialiser] means the compiler expects an implicit Serialiser | |
// needs to be available for A | |
def writeJsonToDisk[A: Serialiser](item: A){ | |
def writeToDisk(x:String){println(s"I saved [$x] to disk, honest!")} | |
// Access the parameter with implicity | |
writeToDisk(implicitly[Serialiser[A]].toJson(item)) | |
} |
This file contains hidden or 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