In my use case I have a class with covariant type Foo[+T] and classes A <: T, B <: T, C <: T,
I need to store a map “A” -> a Foo[A] instance, “B” -> a Foo[B] instance and “C” -> a Foo[C] instance, is this possible in scala?
Currently I declare my map as Map[String, Foo[T]]] but then I can’t add a Foo[A] inside, i’m being told by the compiler that Foo[T] is expected, not Foo[A], which seems caused by the lack of covariance of the Map parameter, is there a solution?
My workaround for now is to de-parameterize Foo and cast in the code, which of course doesn’t please me, I saw also that I could use java collections instead but I would prefer staying with scala.
Thanks in advance for your time
Works for me, even with non-covariant mutable Maps.
If
Foo[T]was not covariant inT, then the last command (m += (2 -> new Foo[A])) would fail.Note that this code works because Tuples are also covariant in their types.