Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert type `Any` to type `Map` in scala

Tags:

scala

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.

like image 358
Liondancer Avatar asked Dec 08 '22 18:12

Liondancer


1 Answers

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")
}
like image 126
prayagupa Avatar answered Dec 27 '22 12:12

prayagupa