Scala version:3.1
I want to create a String -> Int map, that each key may point to many Int.
Therefore I choose map with default mutable Buffer[Int].
But it seems the all the keys always point to the same Buffer[Int]
Notice it is also weird in the first m("a") += 1 that, it print out nothing after this += but default value changed so that it print two 1 in the next println.
Also, how I can fix the problem that mutable.Map's += is overriden by Buffer's +=. I am expecting the map insert a new Buffer if the key doens't exist, then call += of the buffer.
import scala.collection.mutable
val m: mutable.Map[String, mutable.Buffer[Int]] =
mutable.HashMap.empty.withDefaultValue(mutable.Buffer.empty)
m("a") += 1
println(m) // Map()
m("a") = m("a") += 1
println(m) // Map(a -> ArrayBuffer(1, 1))
m("b") = m("b") += 2 // Map(a -> ArrayBuffer(1, 1, 2), b -> ArrayBuffer(1, 1, 2)) , not expecting this, key is correct but
println(m) // Map(a -> ArrayBuffer(1, 1, 2), b -> ArrayBuffer(1, 1, 2))
m("a") = m("a") += 2
println(m) // Map(a -> ArrayBuffer(1, 1, 2, 2), b -> ArrayBuffer(1, 1, 2, 2)) ,
// this is not as I expected. The keys are correct, however their values are all the same ArrayBuffer