Do you remember JsPath pattern matching presented in this article ?
Let’s now go further with something that you should enjoy even more: Json Interpolation & Pattern Matching.
I’ve had the idea of these features for some time in my mind but let’s render unto Caesar what is Caesar’s : Rapture.io proved that it could be done quite easily and I must say I stole got inspired by a few implementation details from them! (specially the @inline implicit conversion for string interpolation class which is required due to a ValueClass limitation that should be removed in further Scala versions)
Please note that string variables must be put between "..." because without it the parser will complain.
Ok, so now it’s really trivial to write Json, isn’t it?
String interpolation just replaces the string you write in your code by some Scala code concatenating pieces of strings with variables as you would write yourself. Kind-of: s"toto ${v1} tata" => "toto + v1 + " tata" + ...
But at compile-time, it doesn’t compile your String into Json: the Json parsing is done at runtime with string interpolation. So using Json interpolation doesn’t provide you with compile-time type safety and parsing for now.
In the future, I may replace String interpolation by a real Macro which will also parse the string at compile-time. Meanwhile, if you want to rely on type-safety, go on using Json.obj / Json.arr API.
Json pattern matching
What is one of the first feature that you discover when learning Scala and that makes you say immediately: “Whoaa Cool feature”? Pattern Matching.
You can write:
12345678910111213
scala>valopt=Option("toto")opt:Option[String]=Some(toto)scala>optmatch{caseSome(s)=>s"not empty option:$s"caseNone=>"empty option"}res2:String=notemptyoption:toto// or direct variable assignement using pattern matchingscala>valSome(s)=opts:String=toto