Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created March 12, 2012 19:11
Show Gist options
  • Save SethTisue/2024057 to your computer and use it in GitHub Desktop.
Save SethTisue/2024057 to your computer and use it in GitHub Desktop.
typeclass code from NEScala talk
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