Search code examples
scalascalatra

Handle Any data type dynamically in Scala


I have a map in Scala returned by a function which is of type Map[String, Any]

For example:

val map: Map[String, Any] = Map("key1" -> "strVal", "key2" -> List[Map[String, Any]](), "key3" -> Map("k1" -> "v1"))

Now the problem is, to work on the value I get corresponding to a key, I've to use asInstanceOf[] every time. For eg,

val key2Hash = map.getOrElse("key3", Map()).getOrElse("k1", "")

throws error because the Map retrieved is of form Any and I have to use asInstanceOf[] for every situation as belows:

val key2Hash = map.getOrElse("key3", Map()).asInstanceOf[Map[String, String]].getOrElse("k1", "")

Is there a better way to do it? Or should I not be starting of with Map[String, Any] at the first place?


Solution

  • Map[String, Any]? You might as well use python directly!

    Joking apart, you can get "nicer" casts syntax using pattern matching:

    map.get("key3") match {
      case Some(anotherMap: Map[String, String]) => ...
      case _ => ...
    }