What’s the best way to create a dynamically growing array in Scala?

But it seems Scala Arrays & Lists doesn’t provide any methods for adding items dynamically due to the immutable nature.

Well, no. Scala Arrays are just Java arrays, so they are mutable:

val arr = Array(1,2)

arr(0) = 3 // arr == Array(3, 2)

But just as Java (and C/C++/C#/etc.) arrays, you can’t change the size of an array.

So you need another collection, which is backed by an array, but does allow resizing. A suitable collection in Scala is scala.collection.mutable.ArrayBuffer, java.util.ArrayList in Java, etc.

If you want to get a List instead of an Array in the end, use scala.collection.mutable.ListBuffer instead.

Leave a Comment