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:


getting the array length like this:


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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.