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

Viewed 40946

I wanted to add items dynamically into an array. But it seems Scala arrays and lists don't provide any methods for adding items dynamically due to the immutable nature.

So I decided to use List data type to make use of this :: method to achieve this. My code look like this

var outList = List(Nil)
val strArray = Array("ram","sam","bam")

for (str<-strArray)
     outList = str :: outList

Though it works in some way, the problem is the new strings are pre-appended into the list. But the ideal requirement is order of the data. Yeah, I know what you are thinking, you can reverse the final result list to get the original order. But the problem is it's a huge array. And I believe it's not a solution though it solves the problem. I believe there should be a simple way to solve this...

And my reason for hacking Scala is to learn the functional way of coding. Having var (mutable type) and populating the list on the fly seems to me is not a functional way of solving things.

How can I do it?

Ideally, I want to achieve something like this in Scala (below the C# code)

List<int> ls = new List<int>();    
for (int i = 0; i < 100; i++)
    ls.Add(i);
7 Answers

We can use ArrayBuffer as suggested. However, i have created a simple program which takes no of parameters for an Array of int and it will let you enter the numbers and finally we are displaying them.

val arraySize = scala.io.StdIn.readLine().toInt
  val arr = new ArrayBuffer[Int]() ++ (1 to arraySize).map{
    i =>
      scala.io.StdIn.readLine().toInt
  }
  println(arr.mkString(","))
Related