Created
March 12, 2012 19:11
-
-
Save SethTisue/2024057 to your computer and use it in GitHub Desktop.
typeclass code from NEScala talk
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
case class Person( | |
name: String, | |
age: Int) | |
case class Restaurant( | |
name: String, | |
brunch: Boolean) | |
// "ser" could just be "apply" | |
trait Serializable[T] { | |
def ser(t: T): String | |
} | |
def serialize[T](t: T) | |
(implicit s: Serializable[T]) = | |
s.ser(t) | |
implicit object PersonIsSerializable | |
extends Serializable[Person] { | |
def ser(p: Person) = | |
"Person(" + p.name + "," + p.age + ")" | |
} | |
implicit object RestaurantIsSerializable | |
extends Serializable[Restaurant] { | |
def ser(r: Restaurant) = | |
"Restaurant(" + r.name + "," + r.brunch + ")" | |
} | |
println(serialize(Person("Seth", 40))) | |
implicit def ListIsSerializable[T : Serializable] = | |
new Serializable[List[T]] { | |
def ser(xs: List[T]) = | |
xs.map(serialize(_)) | |
.mkString("List(", ",", ")") } | |
println(serialize(List(Person("Seth", 40), | |
Person("Kaarin", 43)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment