Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

scala

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?

like image 516
Felix Avatar asked Mar 04 '10 18:03

Felix


People also ask

How do you create multidimensional arrays?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

Which function is used to define a single dimension or multiple dimension array in Scala programming language?

Scala programming language has defined an inbuilt method ofDim() to create a multidimensional array.


2 Answers

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))
like image 61
retronym Avatar answered Oct 23 '22 21:10

retronym


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

val cube = Array.ofDim[Float](8, 8, 8) 
like image 14
Solymosi Avatar answered Oct 23 '22 21:10

Solymosi