Scala create array of empty arrays

2019-08-30 22:33发布

问题:

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?

回答1:

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)


回答2:

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)


回答3:

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.



标签: scala