0

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?

Putt
  • 299
  • 4
  • 10
  • 1
    If there are only two data types you could use an Either[A,B] to represent your data. – Davis Broda May 17 '17 at 13:15
  • It's best to avoid `Any` if you can. If you can't, you can do pattern matching. It does `isInstanceOf` + `asInstanceOf` behind the scenes, but it's more idiomatic. – slouc May 17 '17 at 13:33

1 Answers1

3

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 _ => ...
}
OlivierBlanvillain
  • 7,701
  • 4
  • 32
  • 51