Scala collection.Map cannot be added to

mapscalascala-collections

Why can't I add to a scala.collection.Map? It seems that this trait is pretty useless without this functionality.

Couldn't they have overridden the ++ method in Iterable and reduced the return type to a Map?

P.S. I don't mean that it should be mutable, just that it should be able to return a new Map with an added mapping (or mappings), the same as an immutable.Map.

Best Solution

I'll leave the original answer below, though it is pretty much incorrect, as I didn't understand the question correctly.

Scala's present collection library pretty much enforces different adding methods for mutable/immutable, probably in the hope of making clear in the source code what type of collection is being used. As said, this is being revised in 2.8, and that premise is going away.

That being the case, the abstract classes do not provide the methods you are thinking of, because they might exist for immutable but not for mutable, and vice versa. Or they might have the same name, but different implementations.

And, therefore, it would be impossible to provide them in the base class.

But, furthermore, notice that, this way, if you receive a scala.collection.map, you cannot screw it up by treating it as mutable when you received an immutable, or vice versa.

And, now, for the wrong answer. :)

You can (no, you can't -- the code below uses scala.collection.imutable.Map).

scala> val x = Map(1 -> 'a', 2 -> 'b')
x: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b)

scala> x ++ Map(3 -> 'c')
res5: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b, 3 -> c)

scala> var y = x
y: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b)

scala> y += (3 -> 'c')

scala> y
res7: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b, 3 -> c)

scala> x + (3 -> 'c')
res8: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b, 3 -> c)
Related Question