10.8. Make ArrayBuffer Your “Go To” Mutable Sequence

Problem

You want to use a general-purpose, mutable sequence in your Scala applications.

Solution

Just as the Vector is the recommended “go to” class for immutable, sequential collections, the ArrayBuffer class is recommended as the general-purpose class for mutable sequential collections. (ArrayBuffer is an indexed sequential collection. Use ListBuffer if you prefer a linear sequential collection that is mutable. See Recipe 10.2, for more information.)

To use an ArrayBuffer, first import it:

import scala.collection.mutable.ArrayBuffer

You can then create an empty ArrayBuffer:

var fruits = ArrayBuffer[String]()
var ints = ArrayBuffer[Int]()

Or you can create an ArrayBuffer with initial elements:

var nums = ArrayBuffer(1, 2, 3)

Like other mutable collection classes, you add elements using the += and ++= methods:

scala> var nums = ArrayBuffer(1, 2, 3)
nums: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3)

// add one element
scala> nums += 4
res0: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4)

// add two or more elements (method has a varargs parameter)
scala> nums += (5, 6)
res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 4, 5, 6)

// add elements from another collection
scala> nums ++= List(7, 8)
res2: scala.collection.mutable.ArrayBuffer[Int] =
      ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8)

You remove elements with the -= and --= methods:

// remove one element
scala> nums -= 9 res3: scala.collection.mutable.ArrayBuffer[Int] ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.