Match to the n-th element of a list in Scala

Viewed 3555

What is the best Scala idiom for matching a value to the n-th element of a list?

The naive approach obviously doesn't work:

scala> val list = List(5,6,7)
list: List[Int] = List(5, 6, 7)

scala> val x = 7
x: Int = 7

scala> x match { case list(2) => true; case _ => false }
<console>:10: error: value list is not a case class constructor, nor does it have an       unapply/unapplySeq method
   x match { case list(2) => true; case _ => false }

To clarify- this question is not about how to compare a value to the n-th element of a list - it is specifically about whether it can be done using matching.

4 Answers
Related