【问题标题】:Why mutable.Set.empty ++= treeSet instead of ++?为什么 mutable.Set.empty ++= treeSet 而不是 ++?
【发布时间】:2018-01-19 15:15:14
【问题描述】:

在阅读《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并返回xs的值,即当我们调用时有一个副作用++= 方法。

然而,为了使这个解释有效,mutable.Set.empty 必须是一个左值或其他东西,即它不是一个常量值。但我不这么认为。

谁能解释为什么我们mutable.Set.empty ++= treeSet 是一个有效的表达式?

【问题讨论】:

  • 为什么你认为mutable.Set.empty 是一个常数? mutable.Set.empty 实际上是一个返回新空集的函数。 scala-lang.org/api/2.12.0/scala/collection/mutable/…
  • 感谢您的回复。但我仍然对左值和右值的概念感到困惑。在 Scala 中,函数生成的值可以赋值吗?而在这种情况下,为什么我们使用++= 而不是++

标签: scala collections mutable


【解决方案1】:

它说当我们写 xs ++= ys 时,它将 ys 的所有元素添加到 xs 并返回 xs 的值

如果有++= 方法,它只是调用这个方法。这就是这里发生的事情,因为there is such a method for collection.mutable.Set

如果没有这样的方法,xs 确实需要是一个变量(尽管“返回xs 的值”应该替换为“将结果分配给xs”)。

【讨论】:

    【解决方案2】:

    ++++= 方法之间的主要区别在于,第一个方法创建新集合,而第二个方法只是将 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)
    

    所以,答案 - 是的,++= 是有效的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2017-11-08
      • 2011-01-28
      • 1970-01-01
      • 2011-12-22
      • 2010-12-12
      • 2010-10-11
      相关资源
      最近更新 更多