Trying to declare an array of a certain size in Scala

3.3k views Asked by At
var arr = Array[Int](arr_size)
println(arr_size + " " + arr.size)

arr_size is 30 but arr.size is 1? Why is this?

I am trying to declare an empty array that I can fill in later at designated indexes.

3

There are 3 answers

0
Suma On BEST ANSWER

Array[Int](arr_size) creates an array with one element, arr_size, and is commonly written as Array(arr_size), assuming arr_size type is Int.

Use this instead:

Array.ofDim[Int](arr_size).

You could also use more functional approach and fill the array directly during initialization, e.g. by Array.tabulate.

0
Laksitha Ranasingha On

Alternatively you can do new Array[Int](arr_size)

0
elm On

For creating an Array[Int] of a given size and initialize its values for instance to 0, consider also these other API based approaches,

var arr = Array.fill(arr_size)(0)

and

var arr = Array.tabulate(arr_size)(_ => 0)

Note type Int of 0 determines the type of the Array. Yet a full declaration with type includes

Array.fill[Int](arr_size)(0)
Array.tabulate[Int](arr_size)(_ => 0)