简体   繁体   中英

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
      }  
   }

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM