Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If using a mere <code>List</code> of <code>List</code> (which in itself cannot guarantee that every sub list is of the same size) is not a problem for you, and you are only concerned with easy syntax and avoiding errors at creation-time, scala has many ways to create nice syntax constructs.</p> <p>One such possibility would be a simple helper:</p> <pre><code>object Matrix { def apply[X]( elements: Tuple3[X, X, X]* ): List[List[X]] = { elements.toList.map(_.productIterator.toList.asInstanceOf[List[X]] ) } // Here you might add other overloads for Tuple4, Tuple5 etc if you need "matrixes" of those sizes } val x = Matrix( (3, 5, 7), (0, 4, 9), (1, 8, 6) ) </code></pre> <p>About your concerns:</p> <blockquote> <p>It repeats "List" over and over again (like there could be anything else besides List)</p> </blockquote> <p>Not the case here.</p> <blockquote> <p>It requires to omit trailing , in every List invocation</p> </blockquote> <p>Unfortunately that is still true here, not much you can do given scala's syntactic rules.</p> <blockquote> <p>If I screw up and insert something besides List() in the middle of array, it will go okay with compiler, but type of x would silently become List[Any] instead of List[List[Int]]:</p> </blockquote> <pre><code>val x = List( List(3, 5, 7), List(0, 4), 9, // &lt;= OK with compiler, silently ruins x List(1, 8, 6) ) </code></pre> <p>The equivalent code now faile to compile:</p> <pre><code>scala&gt; val x = Matrix( | (3, 5, 7), | (0, 4), 9, | (1, 8, 6) | ) &lt;console&gt;:10: error: type mismatch; found : (Int, Int) required: (?, ?, ?) (0, 4), 9, </code></pre> <p>And finally if you want to explicitly specify the type of elements (say that you want to protect against the possibility of inadvertently mixing <code>Int</code>s and <code>Double</code>s), you only have to specify <code>Matrix[Int]</code> instead of the ugly <code>List[List[Int]]</code>:</p> <pre><code>val x = Matrix[Int]( (3, 5, 7), (0, 4, 9), (1, 8, 6) ) </code></pre> <p>EDIT: I see that you replaced <code>List</code> with <code>Array</code> in your question. To use arrays all you have to use is to replace <code>List</code> with <code>Array</code> and <code>toList</code> with <code>toArray</code> in my code above.</p>
 

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