如何在 scala 中获取(不可变和可变)集合的列表?
我尝试构建一个(可变和不可变)集合的列表。编译器遇到麻烦,因为它无法确定该列表的类型。我一直认为我可以连接任何类型的列表,并且新列表的类型是连接列表的超类型。在下面的示例中,我定义了一些列表。您可以看到编译器给出的这些列表的类型:
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]]
现在我使用 :::
运算符连接这些列表:
val intStringList = intList:::stringList //List[Any]
val intMSetList = intList:::mSetList //List[Any]
val intISetList = intList:::iSetList //List[Any]
正如预期的那样,编译器计算一个公共超类型 (List[Any ]
) 两个列表。但以下内容无法编译:
val iSetmSetList = iSetList:::mSetList //type error
但如果我显式“转换”这两个列表,它就会起作用:
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]]
为什么我必须帮助编译器获取该列表的正确类型?为什么它会产生错误而不是简单地使用 List[Any]
键入它?理论上不可能计算类型 List[scala.collection.Set[Int]]
还是编译器中的一种错误?
非常感谢您的回答:-)
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 :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个错误,并在夜间版本中修复,正如 huynhjl 怀疑的那样:
It was a bug, and is fixed in nightly versions, as huynhjl suspected: