views:

894

answers:

2

Hello everyone,

in Scala 2.8 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 have changed in 2.8 and that the old arrays are deprecated, but are there multiple ways to do it now and if yes, which is best?

Hoping for quick answers with short examples :)

+15  A: 

Like so:

scala> Array(Array(1, 2), Array(2, 3))
res4: Array[Array[Int]] = Array(Array(1, 2), Array(2, 3))

scala> res4.getClass
res5: java.lang.Class[_] = class [[I

scala> Array.fill(2, 2, 2)(0.0) 
res6: 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 a = new Array[Array[Double]](10)
a: Array[Array[Double]] = Array(null, null, null, null, null, null, null, null, null, null)

scala> a(0) = Array(10.0, 20.0)                  

scala> a(0)(0)
res10: Double = 10.0

UPDATE

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))
retronym
Very nice (and quick!)
Felix
A: 

It's deprecated. Companion object exports factory methods ofDim: val cube = Array.ofDim[Float](8, 8, 8)

Solymosi