简体   繁体   中英

Scala printing uninitialised array

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM