Reputation: 5223
Printing uninitialised array results in size of array, how is this working ? I am iterating over all elements so I expect it to throw error (compile or runtime ) because there is no element to iterate over. To me this is leading error prone code but If this is language feature is there any advantage in this case ?
val array:Array[Int] = Array(5)
array.foreach(x => println(x))
Output : 5
Update: It was confusing because Array(1, 2, 3) creates an array with elements 1, 2 and 3 while Array(1) declares array with 1 element.
Upvotes: 0
Views: 45
Reputation: 15345
If your intention is to create an Array that contains 5 elements with some default values, you can do something like:
> Array.fill[Byte](5)(0)
Array(0, 0, 0, 0, 0)
Upvotes: 2
Reputation: 280182
Array(5)
isn't an empty 5-element array; it's an array whose only element is 5
. You're printing the 5
.
If you wanted to create a 5-element array, that would be new Array(5)
. This array's elements will be initialized to 0
by default, so you'd see 0
5 times with that array.
Upvotes: 5