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:
Array
),
in every Array invocationIf 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?
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.
Scala has a method Array. ofDim to create a multidimensional array. This approach can be used to create arrays of up to five dimensions.
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.
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]] = ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With