ListBuffer: How to create a mutable List in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.2, “How to Create a Mutable List in Scala (ListBuffer)”

Problem

You want to use a mutable list — a LinearSeq, as opposed to an IndexedSeq — but a Scala List isn’t mutable.

Solution: ListBuffer

Use the Scala ListBuffer class, and convert the ListBuffer to a List when needed. The following examples demonstrate how to create a ListBuffer, and then add and remove elements, and then convert it to a List when finished:

import scala.collection.mutable.ListBuffer

var fruits = new ListBuffer[String]()

// add one element at a time to the ListBuffer
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

// add multiple elements
fruits += ("Strawberry", "Kiwi", "Pineapple")

// remove one element
fruits -= "Apple"

// remove multiple elements
fruits -= ("Banana", "Orange")

// remove multiple elements specified by another sequence
fruits --= Seq("Kiwi", "Pineapple")

// convert the ListBuffer to a List when you need to
val fruitsList = fruits.toList

Discussion

Because a List is immutable, if you need to create a list that is constantly changing, the preferred approach is to use a ListBuffer while the list is being modified, then convert it to a List when a List is needed.

The ListBuffer Scaladoc states that a ListBuffer is “a Buffer implementation backed by a list. It provides constant time prepend and append. Most other operations are linear.” So, don’t use ListBuffer if you want to access elements arbitrarily, such as accessing items by index (like list(10000)); use ArrayBuffer instead. See Recipe 10.4, “Understanding the Performance of Collections” for more information.

Although you can’t modify the elements in a List, you can create a new List from an existing one, typically prepending items to the original list with the :: method:

scala> val x = List(2)
x: List[Int] = List(2)

scala> val y = 1 :: x
y: List[Int] = List(1, 2)

scala> val z = 0 :: y
z: List[Int] = List(0, 1, 2)

This is discussed more in Recipe 11.3, “Adding Elements to a List”.