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.
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.
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)
Array[Int](arr_size)
creates an array with one element,arr_size
, and is commonly written asArray(arr_size)
, assumingarr_size
type isInt
.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
.