Reputation: 1108
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...
Upvotes: 0
Views: 98
Reputation: 12783
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.
Upvotes: 1
Reputation: 7845
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
Upvotes: 0