It seems the type of Nil is not polymorphic. How do I correct this function:
scala> def last[A](a:List[A]) : A =
| a match {
| case _ :: tail => last(tail)
| case Nil => Nil[A]
| }
<console>:8: error: object Nil does not take type parameters.
case Nil => Nil[A]
UPDATE:
scala> def last[A](a : List[A] ) : Option[A] =
| a match {
| case head :: Nil => Some(head)
| case _ :: tail => last(tail)
| case Nil => None
| }
Nilis an object, not a type. SoNil[A]doesn’t make any sense.An empty list does not have a last element. As such invoking
lastonNilshould throw an error.Alternatively you could have
lastreturn anOption[A]as shown below: