This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one the shortest recipes in the book, Recipe 11.8, “How to Create an Array Whose Size Can Change (ArrayBuffer)”
You want to create an array whose size can change, i.e., a completely mutable array.
Array is mutable in that its elements can change, but its size can’t change. To create a mutable, indexed sequence whose size can change, use the
To use an
ArrayBuffer, import it into scope and then create an instance. You can declare an
ArrayBuffer without initial elements, and then add them later:
import scala.collection.mutable.ArrayBuffer var characters = ArrayBuffer[String]() characters += "Ben" characters += "Jerry" characters += "Dale"
You can add elements when you create the
ArrayBuffer, and continue to add elements later:
// initialize with elements val characters = collection.mutable.ArrayBuffer("Ben", "Jerry") // add one element characters += "Dale" // add two or more elements (method has a varargs parameter) characters += ("Gordon", "Harry") // add multiple elements with any TraversableOnce type characters ++= Seq("Andy", "Big Ed") // append one or more elements (uses a varargs parameter) characters.append("Laura", "Lucy")
Those are the most common ways to add elements to an
ArrayBuffer (and other mutable sequences). The next recipe demonstrates methods to delete
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:
You can find the Scala Cookbook at these locations: