11.2. Creating a Mutable List

Problem

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

Solution

Use a ListBuffer, 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 for more information.

Although you can’t modify the elements ...

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.