Mutable Scala arrays (adding elements to arrays)

Just a quick note today that if you want to create a mutable Scala array — particularly an array that can grow in size after you first declare it — you need to use the Scala ArrayBuffer class instead of the Array class, which can’t grow.

Here’s a short example that shows how to instantiate an ArrayBuffer object, then add elements to it:

import scala.collection.mutable.ArrayBuffer

var fruits = ArrayBuffer[String]()
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

Once you have an ArrayBuffer object, you can generally use it like an Array, getting elements like this:

println(fruits(0))

getting the array length like this:

println(fruits.length)

and so on. You can also cast an ArrayBuffer to an Array using its toArray method.

Again, the only trick here is knowing that you can’t add elements to a Scala Array, and therefore, if you want to create an array that can be resized, you need to use the ArrayBuffer class instead.