How to use mutable collections in Scala
For both immutable and mutable collections, :+
and +:
create new collections. If you want mutable collections that automatically grow, use the +=
and +=:
methods defined by collection.mutable.Buffer
.
Similarly, map
returns a new collection — look for transform
to change the collection in place.
map
operation applies the given function to all the elements of collection, and produces a new collection.
The operation you are looking for is called transform
. You can think of it as an in-place map
except that the transformation function has to be of type a -> a
instead of 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)