Getting value at index
We cannot do random indexing on a linked list. We have to traverse the list and keep counting until we reach the element or are presented with an error.
Before we look at the method, let's look at Scala's tuple matching. For example, consider the following snippet:
scala> val tup = (1, l) tup: (Int, ch02.mylist.List[Int]) = (1,::(1,::(2,::(3,::(4,Nil))))) scala> tup match { | case (i, x :: xs) => s"i = ${i}, x = ${x}" | } <console>:19: warning: match may not be exhaustive. It would fail on the following input: (_, Nil) tup match { ^ res20: String = i = 1, x = 1
The warning is issued, as we are not handling the case, when the second element of the tuple is an empty list. As the preceding code snippet is merely illustrative, we can live with it.
The following diagram shows how tuple matching works:

We have a tuple tup
holding Int
and List[Int]
. As shown in the diagram...