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?

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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).
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)

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.