15

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 :-)

axel22
  • 32,045
  • 9
  • 125
  • 137
Jan
  • 153
  • 3
  • 4
    That makes me think of http://stackoverflow.com/questions/5734755/scala-type-widening-inference-of-foott-t-t which was fixed with https://issues.scala-lang.org/browse/SI-4501. Worth a shot trying with a nightly more recent than 6/25? – huynhjl Jul 15 '11 at 14:45

1 Answers1

5

It was a bug, and is fixed in nightly versions, as huynhjl suspected:

Welcome to Scala version 2.10.0.r25234-b20110705020226
  (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24)
Type in expressions to have them evaluated.
Type :help for more information.
. . .
scala> val iSetmSetList = iSetList:::mSetList //type error
iSetmSetList: List[scala.collection.Set[Int]] = List(Set(1, 2, 3), Set(2, 1, 3))
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407