David Portabella
David Portabella

Reputation: 12740

scala mutable Map withDefaultValue strange behaviour

I have this example which uses a mutable HashMap.withDefaultValue. withDefaultValues provides a way to return a value even if the key does not exist, but it should not modify the collection. in any case, there is a conflicting behaviour, as map.size returns 0, and at the same time map(key) returns a value.

how is this possible?

import scala.collection.mutable

val map = mutable.HashMap[String, mutable.Map[Int, String]]()
          .withDefaultValue(mutable.HashMap[Int, String]())

map("id1")(2) = "three"
println(map.size)        // 0                   (expected)
println(map)             // Map()               (expected)
println(map("id1"))      // Map(2 -> three)     (unexpected)
println(map("id1")(2))   // three               (unexpected)

Upvotes: 1

Views: 115

Answers (1)

Reactormonk
Reactormonk

Reputation: 21740

It's possible to factor out defaultValue because it's passed as a value.

import scala.collection.mutable

val defaultValue = mutable.HashMap[Int, String]()
val map = mutable.HashMap[String, mutable.Map[Int, String]]()
          .withDefaultValue(defaultValue)

map("id1")(2) = "three"

Which gives you

println(defaultValue)    // Map(2 -> three)

... which should explain the rest of the behaviour. And that's exactly why I recommend immutable data structures ;-)

Upvotes: 2

Related Questions