W.P. McNeill W.P. McNeill - 10 months ago 72
Scala Question

How do I create multidimensional Vectors in Scala?

I want to work with an immutable indexed multidimensional array. The structure that makes sense is a


scala> val v = Vector[Vector[Int]](Vector[Int](1,2,3), Vector[Int](4,5,6), Vector[Int](7,8,9))
v: scala.collection.immutable.Vector[Vector[Int]] = Vector(Vector(1, 2, 3), Vector(4, 5, 6), Vector(7, 8, 9))

It would be nice to create an empty array just by specifying the dimensions, like you can with

scala> a = Array.ofDim[Int](3,3)
a: Array[Array[Int]] = Array(Array(0, 0, 0), Array(0, 0, 0), Array(0, 0, 0))

However, there is no
, function, and I can't find an equivalent.

Is there an equivalent of
for immutable objects? If not, why not?

Answer Source

Each standard collection class has a companion object with factory methods, including fill. By example:

Vector.fill(3, 3)( 0 )

See the relevant scaladoc

Note that for some reason the scala doc is broken in 2.9.2, and the fill method and friends are missing (this is why I linked the scaladoc for version 2.9.1)