Anne
Anne

Reputation: 163

How do I create a 2d int array with different lengths in scala?

How do I do the scala equivalent of this java code

int[][] vals = new int[4][];
for (int i=0; i < vals.length; i++) {
  vals[i] = new int[1 + 2*i];
}

The Array.ofDim method takes two parameters

Upvotes: 4

Views: 231

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

Like this:

Array.tabulate(4)(i => Array.ofDim[Int](1 + 2 * i))

It will be much slower, however. If this code is in a critical path, you should do a while loop to make it much like in Java.

Upvotes: 3

Moritz
Moritz

Reputation: 14212

One way to do this would be:

Array.tabulate(4)(i => new Array[Int](1 + 2 * i))

Upvotes: 3

Related Questions