Reputation: 9183
I'm very new to Scala so I apologize for asking stupid questions. I'm coming from scripting languages such as python, perl, etc. that let you get away w/ a lot.
How do I create a map which contains a map? In Python, I can create the following:
{ 'key': { 'data': 'value' }}
...or in perl
%hash = ( 'key' => ( 'data' => 'value' ));
Also, what is the difference between Map and scala.collection.mutable/immutable.Map, or is there a difference?
Upvotes: 1
Views: 177
Reputation: 42045
A slightly more simple way to create a map of maps:
Map("german" -> Map(1 -> "eins", 2 -> "two"),
"english" -> Map(1 -> "one", 2 -> "two"))
This way you do not have to specify the type explicitly. Regarding the difference between immutable and mutable: Once you have created an immutable map, you cannot change it. You can only create a new map based on the old one with some of the elements changed.
Upvotes: 3
Reputation: 3608
In scala you can create a Map, if you want to fill it at creation, this way:
val mapa = Map(key1 -> value1, key2 -> value2)
Another way would be:
var mapb = Map[Key, Value]()
mapb += key1 -> value1
A map of maps could be created this way:
var mapOfMaps = Map[String, Map[Int, String]]()
mapOfMaps += ("english" -> Map(1 -> "one", 2 -> "two"))
mapOfMaps += ("french" -> Map(1 -> "un", 2 -> "deux"))
mapOfMaps += ("german" -> Map(1 -> "eins", 2 -> "zwei"))
Note that the inner Map is immutable in this example.
Upvotes: 1