How to get a List of (immutable and mutable) Sets in scala?
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 开发者_Python百科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 :-)
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))
精彩评论