I have two sets, one of them lists instances of a derived class. The set type as created is out of my control, I cannot make sure both are Set[A]
instead. The set23
is used in other contexts where I need its type to be Set[B]
. I would like to intersect:
case class A(name: String)
class B(name: String) extends A(name)
val set12 = Set(new A("1"), new A("2"))
val set23 = Set(new B("2"), new B("3"))
set12 intersect set23 // does not work
Error is:
type mismatch; found : scala.collection.immutable.Set[B]
required: scala.collection.GenSet[A]
Note: B <: A, but trait GenSet is invariant in type A.
I am aware Set
is not covariant, is there some clean workaround without rebuilding the sets? Following works, but I would prefer not to use asInstanceOf
:
set12 intersect set23.asInstanceOf[Set[A]]