How can I convert type Any
to type Map
in scala?
Right now I have this val:
poop: scala.collection.immutable.Map[String,Any] = Map(scenario0 -> Map(street -> Bulevard, city -> Helsinki), scenario1 -> Map(street -> Bulevard, city -> Helsinki))
I am trying to extract the Map
objects associated with scenario0
and scenario1
and pass these maps into a function.
1) You can cast Any
to Map[A, B]
.
example, following is Map
of String to another Map
scala> val mapping : Map[String, Any] = Map("key1" -> Map ("key1.1" -> "value1"), "key2" -> Map("key1.2" -> 100))
mapping: Map[String,Any] = Map(key1 -> Map(key1.1 -> value1), key2 -> Map(key1.2 -> 100))
scala> mapping("key1")
res1: Any = Map(key1.1 -> value1)
to cast Any
to Map[A, B]
scala> mapping("key1").asInstanceOf[Map[String, Any]]
res3: Map[String,Any] = Map(key1.1 -> value1)
Then pass to the function
scala> def processSomething(mapping: Map[String, Any]) = println(mapping.keys)
processSomething: (mapping: Map[String,Any])Unit
scala> processSomething(mapping("key1").asInstanceOf[Map[String, Any]])
Set(key1.1)
2) Another way is match the result of mainMap("key")
.
This way, you can handle a case when the result somehow is not Map
. (With casting it throws class cast exception.)
Example below
mapping("key1") match {
case valueMap : Map[String, Any] => processSomething(valueMap)
case _ => println("key1 is not Map")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With