Scala Pattern Matching

Am New to Scala , While Surfing i came across the Below Program , But its hard to Understand Could anyone Please explain how it works ?

Example:
// scala> nth(2, List(1, 1, 2, 3, 5, 8))
// res0: Int = 2

object P03 {

def nthRecursive[A](n: Int, ls: List[A]): A = (n, ls) match {
case (0, h :: _ ) => h
case (_, Nil ) => throw new NoSuchElementException
case (n, _ :: tail) => nthRecursive(n - 1, tail)
}
}

Please Tell me how the below Line Works

case (n, _ :: tail) => nthRecursive(n - 1, tail)

Thanks
Esakki

If n is not 0 and if list(ls) is not empty then third as mentioned in third case, it calls itselft(nthRecursive) by sending parameters as n = n-1, ls = ls.tail.
Tail of a list is all items in the list except first item.
h::t - this will store head of list in h and tail of list in t

1 Like