Mahmoud
Mahmoud

Reputation: 401

Scala assign value to Map of Map

Consider var myMap = Map[String,Map[String,Map[String,String]]]().

1) I tried to add entries to this variable as shown below but was unsuccessful: myMap = myMap + ("a" -> ("b1" -> ("c" -> "d", "e" -> "f"))) How may I fix that?

2) Assuming we are done with step 1 above, how can we add add another sub-map somewhere in the structure; say myMap = myMap + ("a" -> ("b2" -> ("g" -> "h")))?

The final result should be something similar to the structure below:

a:{
   b1:{
       c:d, 
       e:f
      },
   b2:{
       g:h
      }  
   }

Upvotes: 0

Views: 205

Answers (1)

jwvh
jwvh

Reputation: 51271

This is going to be easier to do with a mutable collection rather than a mutable variable.

import collection.mutable.Map
val myMap = Map[String,Map[String,Map[String,String]]]()

myMap.update("a", Map("b1" -> Map("c" -> "d", "e" -> "f")))
myMap("a").update("b2", Map("g" -> "h"))
//Map(a -> Map(b2 -> Map(g -> h), b1 -> Map(c -> d, e -> f)))

Upvotes: 4

Related Questions