I have class that needs to be covariant. This class contains a Map, and the key of this map must be use the same T type as my class :
class A
class B extends A
class Container[+T](val content: T) {
val map : Map[T, _] = Map.empty
}
val c1: Container[A] = new Container[B](new B) // needs to compile (covariant)
It does not compile because Map key type parameter is invariant. Is there a workaround for this kind of situation?
Thanks :)
Defining a U type like this, it is working :
class A
class B extends A
class Container[+T](val content: T) {
type U <: T
val map : Map[U,_] = Map.empty
}
val c1: Container[A] = new Container[B](new B)
Or :
class A
class B extends A
class Container[+T](val content: T) {
val map : Map[_<: T,_] = Map.empty
}
val c1: Container[A] = new Container[B](new B)
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