为什么 mutable.Set.empty ++= treeSet 而不是 ++?
Why mutable.Set.empty ++= treeSet instead of ++?
在阅读"Programming in Scala 3/e"这本书时,我陷入了以下问题。
首先,书中解释说,为了从不可变集创建可变集,将代码编写为:
scala> import scala.collections.immutable.TreeSet
scala> val colors = List("blue", "green", "red")
scala> val treeSet = TreeSet(colors)
scala> val mutaSet = mutable.Set.empty ++= treeSet
-> mutaSet: scala.collection.mutable.Set[String] =
Set(red, blue, green, yellow)
scala> val immutaSet = Set.empty ++ mutaSet
-> immutaSet: scala.collection.immutable.Set[String] =
Set(red, blue, green, yellow)
我无法理解的是以下行中++=
方法的使用:
val mutaSet = mutable.Set.empty ++= treeSet
根据the Scala reference,它说当我们写xs ++= ys
时,它将ys
的所有元素添加到xs
和return的值xs
,即我们调用++=
方法时会产生副作用。
然而,为了使这个解释有效,mutable.Set.empty
必须是左值或其他东西,即它不是常量值。但我不这么认为。
谁能解释为什么我们 mutable.Set.empty ++= treeSet
是一个有效的表达式?
it says that when we write xs ++= ys, it adds all elements of ys to xs and return the value of xs
如果有++=
方法,就直接调用这个方法。这就是这里发生的事情,因为 there is such a method for collection.mutable.Set
.
如果没有这样的方法,xs
确实需要是一个变量(尽管"return the value of xs
"应该被"assigns the result to xs
"代替)。
++
和 ++=
方法之间的主要区别在于第一个方法创建新集合,而第二个方法只是将 treeSet
中的元素添加到集合中。如果您需要使用可变集合,则每次都创建新集合是没有意义的。例如:
val treeSet = collection.immutable.TreeSet(1,2)
val mSet = collection.mutable.Set.empty[Int]
mSet ++ treeSet // creates new Set(1, 2) and doesn't change mSet
println(mSet) // Set()
mSet ++= treeSet // adds to mSet all elements from treeSet
println(mSet) // Set(1, 2)
所以,答案 - 是的,++=
有效
在阅读"Programming in Scala 3/e"这本书时,我陷入了以下问题。
首先,书中解释说,为了从不可变集创建可变集,将代码编写为:
scala> import scala.collections.immutable.TreeSet
scala> val colors = List("blue", "green", "red")
scala> val treeSet = TreeSet(colors)
scala> val mutaSet = mutable.Set.empty ++= treeSet
-> mutaSet: scala.collection.mutable.Set[String] =
Set(red, blue, green, yellow)
scala> val immutaSet = Set.empty ++ mutaSet
-> immutaSet: scala.collection.immutable.Set[String] =
Set(red, blue, green, yellow)
我无法理解的是以下行中++=
方法的使用:
val mutaSet = mutable.Set.empty ++= treeSet
根据the Scala reference,它说当我们写xs ++= ys
时,它将ys
的所有元素添加到xs
和return的值xs
,即我们调用++=
方法时会产生副作用。
然而,为了使这个解释有效,mutable.Set.empty
必须是左值或其他东西,即它不是常量值。但我不这么认为。
谁能解释为什么我们 mutable.Set.empty ++= treeSet
是一个有效的表达式?
it says that when we write xs ++= ys, it adds all elements of ys to xs and return the value of xs
如果有++=
方法,就直接调用这个方法。这就是这里发生的事情,因为 there is such a method for collection.mutable.Set
.
如果没有这样的方法,xs
确实需要是一个变量(尽管"return the value of xs
"应该被"assigns the result to xs
"代替)。
++
和 ++=
方法之间的主要区别在于第一个方法创建新集合,而第二个方法只是将 treeSet
中的元素添加到集合中。如果您需要使用可变集合,则每次都创建新集合是没有意义的。例如:
val treeSet = collection.immutable.TreeSet(1,2)
val mSet = collection.mutable.Set.empty[Int]
mSet ++ treeSet // creates new Set(1, 2) and doesn't change mSet
println(mSet) // Set()
mSet ++= treeSet // adds to mSet all elements from treeSet
println(mSet) // Set(1, 2)
所以,答案 - 是的,++=
有效