错误:@tailrec 注释方法不包含递归调用

ale*_*exs 0 recursion scala

运行这段代码时:

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))
Run Code Online (Sandbox Code Playgroud)

,在 Scala 2.10.2 REPL 中,我收到以下错误:

scala> :9: 错误:@tailrec 注释的方法不包含递归调用

    final def lastRecursive[A] (ls:List[A]):A = {
              ^
Run Code Online (Sandbox Code Playgroud)

请帮忙,我不明白我做错了什么。

小智 5

lastRecursive 不是尾递归,但 lr 是。这对我有用:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)