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.


Going after retronym's answer:

If you still want to use list there are a few ways to prepend an item to the list. What you can do is (yes the top part is still wrong):

scala> var outList : List[String] = Nil
outList: List[String] = List()

scala> val strArray = Array("a","b","c")
strArray: Array[java.lang.String] = Array(a, b, c)

scala> for(s <- strArray)      
     | outList = outList :+ s

scala> outList
res2: List[String] = List(a, b, c)

Note the :+ operator. If you rather append, you'd use s +: outList.

Now who says programming in Scala isn't fun? ;)

P.S. Maybe the reason why you'd want to make them immutable is the speed. Handling large data will be more efficient with immutable data types. Am I right?


If you want to use a mutable Buffer, as retronym mentioned. It looks like this:

scala> var outList = scala.collection.mutable.Buffer[String]()
outList: scala.collection.mutable.Buffer[String] = ArrayBuffer()

scala> for(str<-strArray) outList += str                          

scala> outList
res10: scala.collection.mutable.ListBuffer[String] = ListBuffer(ram, sam, bam)

Anyway, perhaps it is better to directly do the things you want to do with the strArray. E.g:

strArray map(_.toUpperCase) foreach(println)

Tags:

Scala