Scala 在从可迭代创建集合时是否必须转换为 Seq?
也许我(再次)喊错了树,但如果通常的做法是将属性类型为 scala.collection.immutable.Set[A],那么您将如何创建其中之一给定一个 scala.Iterable[A] ? 例如:
class ScalaClass {
private var s: scala.collection.immutable.Set[String]
def init(): Unit = {
val i = new scala.collection.mutable.HashSet[String]
//ADD SOME STUFF TO i
s = scala.collection.immutable.Set(i) //DOESN'T WORK
s = scala.collection.immutable.Set(i toSeq : _ *) //THIS WORKS
}
}
有人可以解释为什么有必要通过 Seq
创建不可变集(或者如果不是,那么我该怎么做)?
Perhaps I am barking up the wrong tree (again) but if it is normal practice to have a property typed as a scala.collection.immutable.Set[A]
, then how would you create one of these given a scala.Iterable[A]
? For example:
class ScalaClass {
private var s: scala.collection.immutable.Set[String]
def init(): Unit = {
val i = new scala.collection.mutable.HashSet[String]
//ADD SOME STUFF TO i
s = scala.collection.immutable.Set(i) //DOESN'T WORK
s = scala.collection.immutable.Set(i toSeq : _ *) //THIS WORKS
}
}
Can someone explain why it is necessary to create the immutable set via a Seq
(or if it is not, then how do I do it)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上是因为您正在通过 Set 的伴随对象中应用的“规范工厂方法”创建不可变的 Set,该对象采用序列或“varargs”(如 Set(a,b,c) 中)。 请参阅此:
http://scala- tools.org/scaladocs/scala-library/2.7.1/scala/collection/immutable/Set$object.html
我认为标准库中没有另一个可以做到这一点。
Basically because you're creating the immutable Set through the "canonical factory method" apply in Set's companion object, which takes a sequence, or "varargs" (as in Set(a,b,c)). See this:
http://scala-tools.org/scaladocs/scala-library/2.7.1/scala/collection/immutable/Set$object.html
I don't think there is another to do it in the standard library.
它将制作一个不可变的副本:
It will make an immutable copy: