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; 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