gpt4 book ai didi

scala - 如何在Scala中使用可变集合

转载 作者:行者123 更新时间:2023-12-03 12:04:42 25 4
gpt4 key购买 nike

我想我可能不了解可变集合是如何工作的。我希望通过将映射应用于它们或添加新元素来影响可变集合,但是:

scala> val s: collection.mutable.Seq[Int] = collection.mutable.Seq(1)
s: scala.collection.mutable.Seq[Int] = ArrayBuffer(1)

scala> s :+ 2 //appended an element
res32: scala.collection.mutable.Seq[Int] = ArrayBuffer(1, 2)

scala> s //the original collection is unchanged
res33: scala.collection.mutable.Seq[Int] = ArrayBuffer(1)

scala> s.map(_.toString) //mapped a function to it
res34: scala.collection.mutable.Seq[java.lang.String] = ArrayBuffer(1)

scala> s //original is unchanged
res35: scala.collection.mutable.Seq[Int] = ArrayBuffer(1)

//maybe mapping a function that changes the type of the collection shouldn't work
//try Int => Int

scala> s.map(_ + 1)
res36: scala.collection.mutable.Seq[Int] = ArrayBuffer(2)

scala> s //original unchanged
res37: scala.collection.mutable.Seq[Int] = ArrayBuffer(1)

这种行为似乎与不可变集合并不分离,因此它们何时分别表现出来?

最佳答案

对于不可变和可变集合,:++:创建新集合。如果要使可变集合自动增长,请使用 += 定义的+=:collection.mutable.Buffer方法。

同样,map返回一个新集合-查找transform以更改该集合。

关于scala - 如何在Scala中使用可变集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com