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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

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.