00.scala2014. 3. 28. 13:19
반응형

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 of how to instantiate an ArrayBuffer object, then add elements to the array:

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.

Again, the only trick here is knowing that you can't add elements to a Scala array, and therefore, if you want to grow an array, you need to use the ArrayBuffer class instead.

Posted by 1010