I want to extends a class with a val of mutable.HashMap[] like this:
class Father
class Son extends Father
class C1{
val m = new mutable.HashMap[Int, Father]()
}
class C2 extends C1{
override val m = new mutable.HashMap[Int, Son]()
}
And get an error:
Error:(19, 16) overriding value m in class C1 of type scala.collection.mutable.HashMap[Int,ScalaByExample.Father]; value m has incompatible type override val m = new mutable.HashMapInt, Son
I found that immutable.HashMap
is covariant but mutable.HashMap
is invariant. It works if replace mutable.HashMap
with immutable.HashMap
.
So my two questions are:
How can I make it works using mutable.HashMap?
Why did scala's author design HashMap like this?
Scala collections systematically distinguish between mutable and immutable collections. A mutable collection can be updated or extended in place. This means you can change, add, or remove elements of a collection as a side effect. Immutable collections, by contrast, never change.
There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed. By default, Scala uses the immutable Map. If you want to use the mutable Map, you'll have to import scala. collection.
Lists are immutable whereas arrays are mutable in Scala.
Mutable maps are invariant because writing to them wouldn't be safe otherwise. Consider for example the following function:
def f(o: C1) {
o.m(42) = new Father
}
This method is perfectly well-typed. But if you passed in an instance of C2
as the value for o
, it'd break because a Map[Int, Son]
is not allowed to contain Father
objects. Therefore your definition of C2
is ill-typed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With