Search code examples
scalacollectionsmutable

How to use mutable collections in Scala


I think I may be failing to understand how mutable collections work. I would expect mutable collections to be affected by applying map to them or adding new elements, however:

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)

This behaviour doesn't seem to be separate from the immutable collections, so when do they behave separately?


Solution

  • 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.