I’ve been digging around in the Scala code. It looks like TreeMap uses the following builder class.
class MapBuilder[A, B, Coll <: scala.collection.GenMap[A, B] with scala.collection.GenMapLike[A, B, Coll]](empty: Coll)
extends Builder[(A, B), Coll] {
protected var elems: Coll = empty
def +=(x: (A, B)): this.type = {
elems = (elems + x).asInstanceOf[Coll]
// the cast is necessary because right now we cannot enforce statically that
// for every map of type Coll, `+` yields again a Coll. With better support
// for hk-types we might be able to enforce this in the future, though.
this
}
def clear() { elems = empty }
def result: Coll = elems
}
I don’t understand the cast, but that’s besides the point. It looks as though, for example, when two TreeMaps are ++-ed together, a new TreeMap is instantiated and then all the key-value pairs from both TreeMaps are added. Since TreeMapis immutable, why can’t we start from one of the TreeMaps and just add the items from the other? Is this just because ++works on both immutable and mutable types, so we need to make a defensive copy, and some collections may have more efficient strategies?
If this is our code:
Then
++is defined inTreeMapas:So we start with
aand fold each element ofbinto it to get the final result.In other words, it appears to be doing exactly what you expected. Or did I miss something?