Pattern matching to find last element of list

Viewed 7030

I am trying to find the last element of a list in Scala using pattern matching. I tried following code

def last[A](list: List[A]):A = list match {
 case head :: Nil => head
 case head :: tail => last(tail)
 case _ => Nil
 }

The last case i.e. case _ => Nil is throwing error as type mismatch (found Nil.type require A)

I know this problem can be solved using other methods but using only pattern matching is there a way to solve this?

As the list is of generic type so I cannot replace Nil with default value of type A which can only be determined at runtime.

Removing this line: case _ => Nil is obviously working but with a warning that it will fail in case of Nil argument.

So, how can I handle Nil argument in this scenario?

3 Answers
Related