Skip to content

Instantly share code, notes, and snippets.

@joune
Created February 21, 2017 06:35
Show Gist options
  • Save joune/14bc219ea6556d9ee74d512b41fdfa5a to your computer and use it in GitHub Desktop.
Save joune/14bc219ea6556d9ee74d512b41fdfa5a to your computer and use it in GitHub Desktop.
super simple memo on typeclasses with generics
trait Json[T] {
def toJson(t:T):String
}
implicit object jsonStr extends Json[String] {
def toJson(s:String) = s""""$s""""
}
implicit object jsonInt extends Json[Int] {
def toJson(s:Int) = s"$s"
}
implicit def jsonSet[T:Json] = new Json[Set[T]] {
def toJson(l:Set[T]) = (l map (v => implicitly[Json[T]].toJson(v))).mkString("[",",","]")
}
implicit def jsonMap[T:Json] = new Json[Map[String,T]] {
def toJson(m:Map[String,T]) = (m map { case (k,v) =>
s""""$k":${implicitly[Json[T]].toJson(v)}""" }).mkString("{",",","}")
}
def json[T:Json](v:T) = implicitly[Json[T]].toJson(v)
println(json("a"))
println(json(42))
println(json(Set("a","b")))
println(json(Map("k1" -> Set("a","b"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment