39

How do I create an array of multiple dimensions?

For example, I want an integer or double matrix, something like double[][] in Java.

I know for a fact that arrays changed in Scala 2.8 and that the old arrays are deprecated, but are there multiple ways to do it now and if yes, which is best?

Seth Tisue
  • 29,985
  • 11
  • 82
  • 149
Felix
  • 8,385
  • 10
  • 40
  • 59

3 Answers3

59

Like so:

scala> Array.ofDim[Double](2, 2, 2)
res2: Array[Array[Array[Double]]] = Array(Array(Array(0.0, 0.0), Array(0.0, 0.0)), Array(Array(0.0, 0.0), Array(0.0, 0.0)))

scala> {val (x, y) = (2, 3); Array.tabulate(x, y)( (x, y) => x + y )}
res3: Array[Array[Int]] = Array(Array(0, 1, 2), Array(1, 2, 3))
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
retronym
  • 54,768
  • 12
  • 155
  • 168
  • 2
    Is `Array[Array[Int]]` equivalent to `int[][]` in Java? cause I heard vicious rumors otherwise http://stackoverflow.com/questions/6090684 – Elazar Leibovich May 23 '11 at 09:02
14

It's deprecated. Companion object exports factory methods ofDim:

val cube = Array.ofDim[Float](8, 8, 8) 
JMax
  • 26,109
  • 12
  • 69
  • 88
Solymosi
  • 141
  • 1
  • 2
-1

How to create and use a multi-dimensional array in Scala?

var dd : Array[(Int, (Double, Double))] = Array((1,(0.0,0.0)))