I try to build a list of (mutable and immutable) Sets. The compiler gets into trouble as it cannot figure out the type of that list. I always thought that I can connect Lists of any types and that the type of the new List is a kind of supertype of the connected Lists. In the following example, I define some lists. You can see the types of those lists, given by the compiler:
val intList = List(1) //List[Int]
val stringList = List("ab") //List[java.lang.String]
val mSetList = List(mutable.Set(1, 2, 3)) //List[scala.collection.mutable.Set[Int]]
val iSetList = List(immutable.Set(1, 2, 3)) //List[scala.collection.immutable.Set[Int]]
Now I use the :::
operator to connect these lists:
val intStringList = intList:::stringList //List[Any]
val intMSetList = intList:::mSetList //List[Any]
val intISetList = intList:::iSetList //List[Any]
As expected, the compiler computes a common supertype (List[Any]
) of both lists. But the following does not compile:
val iSetmSetList = iSetList:::mSetList //type error
But if I explicitly "cast" the two lists, it works:
val setList1 : List[scala.collection.Set[Int]] = mSetList //List[scala.collection.Set[Int]]
val setList2 : List[scala.collection.Set[Int]] = iSetList // List[scala.collection.Set[Int]]
val setList = setList1:::setList2 //List[scala.collection.Set[Int]]
Why do I have to help the compiler to get the correct type of that list? And why does it produce an error rather than simply type it with List[Any]
? Is it theoretically impossible to compute the type List[scala.collection.Set[Int]]
or is it a kind of bug in the compiler?
Thanks a lot for your answers :-)