Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a 2D (multi-dimensional) array in Scala

It's easy to initialize a 2D array (or, in fact, any multidimensional array) in Java by putting something like that:

int[][] x = new int[][] {         { 3, 5, 7, },         { 0, 4, 9, },         { 1, 8, 6, }, }; 

It's easy to read, it resembles a 2D matrix, etc, etc.

But how do I do that in Scala?

The best I could come up with looks, well, much less concise:

val x = Array(     Array(3, 5, 7),     Array(0, 4, 9),     Array(1, 8, 6) ) 

The problems I see here:

  • It repeats "Array" over and over again (like there could be anything else besides Array)
  • It requires to omit trailing , in every Array invocation
  • If I screw up and insert something besides Array() in the middle of array, it will go okay with compiler, but type of x would silently become Array[Any] instead of Array[Array[Int]]:

    val x = Array(     Array(3, 5, 7),     Array(0, 4), 9, // <= OK with compiler, silently ruins x     Array(1, 8, 6) ) 

    There is a guard against it, to specify the type directly, but it looks even more overkill than in Java:

    val x: Array[Array[Int]] = Array(     Array(3, 5, 7),     Array(0, 4), 9, // <= this one would trigger a compiler error     Array(1, 8, 6) ) 

    This last example needs Array even 3 times more than I have to say int[][] in Java.

Is there any clear way around this?

like image 801
GreyCat Avatar asked Dec 13 '12 15:12

GreyCat


People also ask

How do you initialize a new 2D array?

Here is how we can initialize a 2-dimensional array in Java. int[][] a = { {1, 2, 3}, {4, 5, 6, 9}, {7}, }; As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.

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

Scala has a method Array. ofDim to create a multidimensional array. This approach can be used to create arrays of up to five dimensions.

How do you declare a multidimensional array?

We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.


1 Answers

Personally I'd suck it up and type out (or cut and paste) "Array" a few times for clarity's sake. Include the type annotation for safety, of course. But if you're really running out of e-ink, a quick easy hack would be simply to provide an alias for Array, for example:

val > = Array  val x: Array[Array[Int]] = >(   >(3, 5, 7),   >(0, 4, 9),   >(1, 8, 6) ) 

You could also provide a type alias for Array if you want to shorten the annotation:

type >[T] = Array[T]  val x: >[>[Int]] = ... 
like image 117
Luigi Plinge Avatar answered Sep 20 '22 05:09

Luigi Plinge