Created
September 22, 2011 21:43
-
-
Save SethTisue/1236139 to your computer and use it in GitHub Desktop.
serialization example (typeclass pattern)
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
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