How do I get the nth element of a Seq?

mySeq.apply(1) is another way to say mySeq(1)

scala> val mySeq = Seq("A", "B", "C")
mySeq: Seq[String] = List(A, B, C)

scala> mySeq(0)
res0: String = A

scala> mySeq(1)
res1: String = B

To avoid index out of bounds,

scala> mySeq(200)
java.lang.IndexOutOfBoundsException: 200
  at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:65)
  at scala.collection.immutable.List.apply(List.scala:84)
  ... 33 elided

lift the sequence,

mySeq.lift(2)
Some(C)

mySeq.lift(200)
None

or in a similar way,

mySeq.drop(2).headOption
Some(C)

mySeq.drop(200).headOption
None

By lifting the sequence we define a partial function from Int onto each value of the sequence. Namely from each position index onto its corresponding value. Hence positions not defined (any negative value or larger than the size of the collection) are mapped onto None, the rest are defined and become Some value.


The method to get the nth element of a Seq is apply:

val mySeq = Seq("A", "B", "C")
mySeq.apply(1) // "B"

Usually, you will never write x.apply(y) and just use shorthand x(y). The Scala compiler will convert it for you.

mySeq(1) // "B"

To avoid potential index out of bounds, you can wrap using Try.

Try(mySeq(x)).toOption

This will return None when x >= 3 and Some(...) when x < 3.

Tags:

Scala