you get IndexOutOfBoundsException
, when you try to access an index greater than number of elements in a collection or less than 0 as the vector starts from index 0.
example below,
scala> val vector = Vector("washington", "iowa", "california")
vector: scala.collection.immutable.Vector[String] = Vector(washington, iowa, california)
scala> vector(0)
res4: String = washington
scala> vector(1)
res5: String = iowa
scala> vector(2)
res6: String = california
you get IndexOutOfBoundsException
if you try to access index < 0
or index >=3
,
scala> vector(3)
java.lang.IndexOutOfBoundsException: 3
at scala.collection.immutable.Vector.checkRangeConvert(Vector.scala:132)
at scala.collection.immutable.Vector.apply(Vector.scala:122)
... 33 elided
how can i fix it?
check if the index you are accessing is lesser than 0
or greater than number of elements
in a vector or use .lift
on collection.
scala> vector.lift(0)
res14: Option[String] = Some(washington)
scala> vector.lift(3)
res15: Option[String] = None
releated question - How to get an Option from index in Collection in Scala?