Scala Array declaration - unintuitive result for apply(0)

How is this possible? I have not created a new array...yet m(0) has a value of 10. AND, m(1) is an ArrayIndexOutOfBounds exception...


val m = Array[Int](10) means an array of type Int with one element 10 bound the variable m. m(n) means the n-th element of m.

Thats why m(1) gives you a ArrayIndexOutOfBounds, m has only one element.

Are you mixing it up with the odd Java syntax for arrays? int[] m = new int[10]; Which is a 10 uninitialized elements array.

Array[Int](10) creates an array with one element, 10. Check it here

Still, in Scala you shouldn't access array elements directly without be aware of exceptions. I would prefer something like:

scala> val array = Array(10)
array: Array[Int] = Array(10)

scala> array.drop(5).headOption
res0: Option[Int] = None

to access the 5th element for instance

Need Your Help

export mysql data to csv file

mysql sql jdbc mysql-error-1045 into-outfile

I am trying to do 2 output data from mysql to a csv file.

Calculating Paint Times of Elements In All Browsers

javascript html

I am trying to calculate the elapsed time an element is painted onto the DOM from the start time of the script or if the specific element was even painted at all. I am inserting a background gradie...