Created
February 21, 2017 06:35
-
-
Save joune/14bc219ea6556d9ee74d512b41fdfa5a to your computer and use it in GitHub Desktop.
super simple memo on typeclasses with generics
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
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