Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created September 22, 2011 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SethTisue/1236139 to your computer and use it in GitHub Desktop.
Save SethTisue/1236139 to your computer and use it in GitHub Desktop.
serialization example (typeclass pattern)
case class Person(name: String, age: Int)
case class Restaurant(name: String, servesBrunch: Boolean)
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 PersonIsJSONable
extends Serializable[Person] {
def ser(p: Person) =
"{ \"person\": { " +
"\"name\": \"" + p.name +
"\", \"age\": " + p.age + " } }"
}
case class Group(people: Person*)
implicit object GroupIsSerializable
extends Serializable[Group] {
def ser(g: Group) =
g.people.map(PersonIsSerializable.ser)
.mkString("Group(", ",", ")")
}
// scala> serialize(Group(Person("Seth", 40), Person("Kaarin", 42)))
// res9: String = Group(Person(Seth,40),Person(Kaarin,42))
implicit def ListIsSerializable[T : Serializable] =
new Serializable[List[T]] {
def ser(xs: List[T]) =
xs.map(serialize(_))
.mkString("List(", ",", ")")
}
// scala> serialize(List(Person("Seth", 40), Person("Kaarin", 42)))
// res1: String = List(Person(Seth,40),Person(Kaarin,42))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment