Matching List and Map in Scala

For a while that I’ve been reading Scala I find it as a strong and powerfull language which helps you to write your application perfectly, it’s not like Java that ties you to follow some arid rules and it’s not like PHP that let you screw in your application(of course you can handle your code in PHP). Programing in Scala is fun as programming Python and it’s powerful as Java!

Scala’s Match syntax is liitle like Switch-Case but you can match value, type, regex, special type of class and more. 

Here is a syntax of matching for List and map in Scala, for finding these codes I search a lot to ! so I wrote these samples for future usage. 

val foobar = Map("foo"->"bar") foobar match {    case map :  scala.collection.Map[_, _] => println(map) }


val foobar = List("foo","bar") foobar match {    case  list:Seq[_] => println(list) }


So maybe you ask that why you need to handle something like this ?

It’s real world senario: I wanna to pass mix value of Map and List and String to function and get JSON string from that. some thing like this :

def toJson(ob: Any):String = {   ob match {     case s : String   => return "\""+ s + "\""     case d:Double   => return "\""+ d.toString + "\""     case map:scala.collection.Map[_, _] => return "{" + ((for((k,v) <- map) yield toJson(k) + ":" + toJson(v) ).reduceLeft(_ + ", " + _) ) + "}"     case list @ List(_*)   => return "[" + ((for (m<-list) yield toJson(m)).reduceLeft(_ + ", " + _) )   + "]" }

Mabye last code doesn’t work probably ! because I write it to just show you how you can use this feature