W.P. McNeill W.P. McNeill - 7 days ago 6
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

Vector
of
Vector
s.

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
Array.ofDim
.

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
Vector.ofDim
, function, and I can't find an equivalent.

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

Answer

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)

Comments