Behaviour of withDefaultValue in mutable.Map

纵然是瞬间 提交于 2019-12-02 18:27:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!