如何在Scala中使用可变集合

Hen*_*son 20 collections scala mutable

我想我可能无法理解可变集合的工作原理.我希望通过将map应用于它们或添加新元素来影响可变集合,但是:

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)
Run Code Online (Sandbox Code Playgroud)

这种行为似乎与不可变集合是分开的,所以它们什么时候单独行为?

Jea*_*let 40

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

同样,map返回一个新集合 - 寻找transform更改集合的位置.


mis*_*tor 6

mapoperation将给定函数应用于集合的所有元素,并生成新集合.

您正在寻找的操作被调用transform.您可以将其视为就地,map除了转换函数必须是类型a -> a而不是a -> b.

scala> import collection.mutable.Buffer
import collection.mutable.Buffer

scala> Buffer(6, 3, 90)
res1: scala.collection.mutable.Buffer[Int] = ArrayBuffer(6, 3, 90)

scala> res1 transform { 2 * }
res2: res1.type = ArrayBuffer(12, 6, 180)

scala> res1
res3: scala.collection.mutable.Buffer[Int] = ArrayBuffer(12, 6, 180)
Run Code Online (Sandbox Code Playgroud)