0

I am trying to create an array where each element is an empty array. I have tried this:

var result = Array.fill[Array[Int]](Array.empty[Int])

After looking here How to create and use a multi-dimensional array in Scala?, I also tried this:

var result = Array.ofDim[Array[Int]](Array.empty[Int])

However, none of these work.

How can I create an array of empty arrays?

Community
  • 1
  • 1
bsky
  • 19,326
  • 49
  • 155
  • 270

3 Answers3

8

You are misunderstanding Array.ofDim here. It creates a multidimensional array given the dimensions and the type of value to hold.

To create an array of 100 arrays, each of which is empty (0 elements) and would hold Ints, you need only to specify those dimensions as parameters to the ofDim function.

val result = Array.ofDim[Int](100, 0)
Score_Under
  • 1,189
  • 10
  • 20
  • As an aside, I've turned `result` into a `val`, since I strongly doubt that it needs to be modified (this would involve *entirely replacing* the array of arrays, rather than just modifying the contents of a sub-array). – Score_Under Jan 18 '16 at 20:26
5

Array.fill takes two params: The first is the length, the second the value to fill the array with, more precisely the second parameter is an element computation that will be invoked multiple times to obtain the array elements (Thanks to @alexey-romanov for pointing this out). However, in your case it results always in the same value, the empty array.

Array.fill[Array[Int]](length)(Array.empty)
lex82
  • 11,173
  • 2
  • 44
  • 69
  • 2
    Be careful: the second argument is _not_ a value, but a _calculation_ which produces a value and will be called for every element. The example given in documentation is `Array.fill(3){ math.random }` which gives 3 different random values. – Alexey Romanov Jan 18 '16 at 20:51
1

Consider also Array.tabulate as follows,

val result = Array.tabulate(100)(_ => Array[Int]())

where the lambda function is applied 100 times and for each it delivers an empty array.

elm
  • 20,117
  • 14
  • 67
  • 113