0

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately I can accept answer only in 9 minutes waiting for that!
2

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) 

1 Comment

I am learning language and experimenting with these things and you got my intention right!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.