2013-08-25 64 views
0

当运行这段代码:错误:@tailrec注释的方法不包含递归调用

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)) 

,在斯卡拉2.10.2 REPL,我得到以下错误:

斯卡拉>:9:错误:@tailrec注解的方法不包含递归调用

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

请帮助,我不明白我在做什么错。

+0

它看起来像你打算把注释放在'lr'而不是'lastRecursive'? – Lee

回答

4

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) 
    } 
} 
+0

谢谢。当我将注释移动到lr时它工作正常! – alexs

相关问题