Is there any way to build dynamic multi-dimensional arrays in Scala? I know arrays in Scala must be initialized in its sizes and dimensions, so I don\'t want that. The data stru
If you want to do something like
a(5) = // result of some computation
then you'll need to use something from the mutable collections hierarchy. I'd suggest ArrayBuffer
.
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer
scala> val a = ArrayBuffer.fill(3,3)(0)
a: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[Int]] = ArrayBuffer(ArrayBuffer(0, 0, 0), ArrayBuffer(0, 0, 0), ArrayBuffer(0, 0, 0))
scala> a(2)(1) = 4
scala> a(0) = ArrayBuffer(1,2,3)
scala> a
res2: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[Int]] = ArrayBuffer(ArrayBuffer(1, 2, 3), ArrayBuffer(0, 0, 0), ArrayBuffer(0, 4, 0))
Note that fill
lets you automatically create and initialize up to 5D structures. Note also that you can extend the length of these, but it won't extend the entire multidimensional structure, just the one you add to. So, for example,
scala> a(2) += 7 // Add one element to the end of the array
res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 4, 0, 7)
scala> a
res4: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[Int]]
= ArrayBuffer(ArrayBuffer(1, 2, 3), ArrayBuffer(0, 0, 0), ArrayBuffer(0, 4, 0, 7))