Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing a 2D (multi-dimensional) array in Scala
    primarykey
    data
    text
    <p>It's easy to initialize a 2D array (or, in fact, any multidimensional array) in Java by putting something like that:</p> <pre><code>int[][] x = new int[][] { { 3, 5, 7, }, { 0, 4, 9, }, { 1, 8, 6, }, }; </code></pre> <p>It's easy to read, it resembles a 2D matrix, etc, etc.</p> <p>But how do I do that in Scala?</p> <p>The best I could come up with looks, well, much less concise:</p> <pre><code>val x = Array( Array(3, 5, 7), Array(0, 4, 9), Array(1, 8, 6) ) </code></pre> <p>The problems I see here:</p> <ul> <li>It repeats "Array" over and over again (like there could be anything else besides <code>Array</code>)</li> <li>It requires to omit trailing <code>,</code> in every Array invocation</li> <li><p>If I screw up and insert something besides <code>Array()</code> in the middle of array, it will go okay with compiler, but type of <code>x</code> would silently become <code>Array[Any]</code> instead of <code>Array[Array[Int]]</code>:</p> <pre><code>val x = Array( Array(3, 5, 7), Array(0, 4), 9, // &lt;= OK with compiler, silently ruins x Array(1, 8, 6) ) </code></pre> <p>There is a guard against it, to specify the type directly, but it looks even more overkill than in Java:</p> <pre><code>val x: Array[Array[Int]] = Array( Array(3, 5, 7), Array(0, 4), 9, // &lt;= this one would trigger a compiler error Array(1, 8, 6) ) </code></pre> <p>This last example needs <code>Array</code> even 3 times more than I have to say <code>int[][]</code> in Java.</p></li> </ul> <p>Is there any clear way around this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload