Reputation: 3460
This may sound easy, but I just can't get it right.
How to create a 2 dimensional array with size 100 by 60 in Scala? Supposed I have class called Abcd and I want to create a 2 dimensional array of Abcd. I tried with the following code but doesn't work.
var myArray = new Array[Array[Abcd]](100,60)
It complains "too many arguments for constructor Array"
Upvotes: 20
Views: 24317
Reputation: 426
Or if you prefer to have your array start with ABCD's instead of nulls
Array.fill[ABCD](100,6) { new ABCD }
or if the ABCD vary in some regular way by position
Array.tabulate[ABCD](100,6) { (i,j) => new ABCD(i,j) }
Upvotes: 26
Reputation: 3591
I know this question is answered but one problem I ran into was that @alexwriteshere's solution and @Chick's solution was only good if you wanted a matrix.
To be able to create a two-dimensional array with (if viewed as first number of rows then number of columns), do something like this:
val array = Array.ofDim[Array[Char]](2)
array(0) = Array.ofDim[Char](10)
array(1) = Array.ofDim[Char](20)
Upvotes: 4
Reputation: 10667
The currently recommended way is to use ofDim
:
var myArray = Array.ofDim[Abcd](100, 60)
Upvotes: 43