Behavior withDefaultValue in mutable.Map

Can someone explain how the default value works in a mutable map?

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)

The card is empty, no keys.

scala> mmap
res2: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map()

But the key that I just tried to edit shows the data.

scala> mmap("a")
res3: scala.collection.mutable.Set[String] = Set(b)

Why is a res2blank card, but mmap("a")it matters?

-1
source share
1 answer

By changing a key that does not exist on the map, you basically change the default value, rather than adding a new key.

Suppose you want to add some things to install using the key aon your card.

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 mmaphas 2 elements, but still no keys. Now you are changing another non-existent key:

// Still changind default value
mmap( "c" ) += "c1"

-

// Printing default value
println( mmap("a") )
// Result => Set(c, c1, b)

// Creating a new key
mmap("b") = mutable.Set[ String ]( "b1", "b2" )

mmap.foreach( println )
// Result => (b,Set(b1, b2))
+3

Source: https://habr.com/ru/post/1687409/


All Articles