3

just read Scala collection implementation and noticed a subtile difference:

  • immutable HashMap : class HashMap[A, +B]()
  • mutable HashMap : class HashMap[A, B]()

Could you please explain me why the immutable's value type is covariant while the mutable's one is not ?

Thanks for your help

ogen
  • 802
  • 2
  • 7
  • 23

2 Answers2

6

If the mutable map were covariant, it would be possible to do something like this:

val m1: mutable.Map[String, Int] = mutable.Map.empty[String, Int]
val m2: mutable.Map[String, Any] = m1
m2 += ("foo" -> "bar")
m1("foo") // returns "bar" out of a Map[String, Int]???
Joe K
  • 18,204
  • 2
  • 36
  • 58
3

The mutable HashMap has methods taking B as argument, e.g. def update(key: A, value: B): Unit. Presence of such methods means B can't be covariant, or you could write

val map: mutable.HashMap[Int, AnyRef] = mutable.HashMap.empty[Int, String]
map.update(0, new AnyRef) // call update(Int, AnyRef) where (Int, String) is expected

The immutable one doesn't.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487