问题
Can anyone explain how a default value in mutable map works?
scala> val mmap = mutable.Map[String, mutable.Set[String]]().withDefaultValue{mutable.Set[String]()}
mmap: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map()
scala> mmap("a") += "b"
res1: scala.collection.mutable.Set[String] = Set(b)
Map is empty, no keys.
scala> mmap
res2: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map()
But the key I just tried to edit is showing data.
scala> mmap("a")
res3: scala.collection.mutable.Set[String] = Set(b)
Why is res2
an empty map but mmap("a")
have a value?
回答1:
By modifying key that does not exist in the map you basically changing the default value, not adding a new key.
Let's say you want to add some stuff to set with key a
in your map.
val mmap =
mutable.Map[ String, mutable.Set[ String ] ]()
.withDefaultValue( mutable.Set[ String ]() )
// Changind default value
mmap( "a" ) += "b"
mmap( "a" ) += "c"
Now the default value of mmap
has 2 elements but still no keys. Now you 'change' the other nonexisting key:
// Still changind default value
mmap( "c" ) += "c1"
In reality you are still changing the default value
// Printing default value
println( mmap("a") )
// Result => Set(c, c1, b)
In order to create a real key use assignment
// Creating a new key
mmap("b") = mutable.Set[ String ]( "b1", "b2" )
mmap.foreach( println )
// Result => (b,Set(b1, b2))
来源:https://stackoverflow.com/questions/46650121/behaviour-of-withdefaultvalue-in-mutable-map