Scala array indexing

Scala arrays are 0-based and are accessed with parenthesis, rather than square brackets:

val x = Array(1,2,3)

x(0)

You can also index them inline, or use the same syntax to instantiate other collections:

scala> List(1,2,3)(0)
res10: Int = 1

scala> List(1,2,3)(1)
res11: Int = 2

Unlike languages like Python and R, collections will not wrap around:

scala> List(1,2,3)(3)
java.lang.IndexOutOfBoundsException: 3
  at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:51)
  at scala.collection.immutable.List.apply(List.scala:83)
  ... 33 elided

scala> List(1,2,3)(-1)
java.lang.IndexOutOfBoundsException: -1
  at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:51)
  at scala.collection.immutable.List.apply(List.scala:83)
  ... 33 elided

Leave a Reply

Your email address will not be published.