alexs
alexs

Reputation: 406

error: @tailrec annotated method contains no recursive calls

When running this piece of code:

object P01 {
    @annotation.tailrec
    final def lastRecursive[A] (ls:List[A]):A = {
        def lr[A] (l:List[A]):A = l match {
            case h :: Nil  => h
            case _ :: tail => lr(tail)
            case _         => throw new NoSuchElementException  
        }
        lr(ls)
    }
}

P01.lastRecursive(List(1,2,3))

,in scala 2.10.2 REPL, I get the following error:

scala> :9: error: @tailrec annotated method contains no recursive calls

    final def lastRecursive[A] (ls:List[A]):A = {
              ^

Please help, I don't understand what am I doing wrong.

Upvotes: 0

Views: 593

Answers (1)

Mario Lenz
Mario Lenz

Reputation: 634

lastRecursive isn't tail recursive but lr is. This worked for me:

object P01 {
    final def lastRecursive[A] (ls:List[A]):A = {
        @annotation.tailrec
        def lr[A] (l:List[A]):A = l match {
            case h :: Nil  => h
            case _ :: tail => lr(tail)
            case _         => throw new NoSuchElementException  
        }
        lr(ls)
    }
}

Upvotes: 5

Related Questions