应用 @tailrec 我从 scala 编译器收到错误:“无法优化 @tailrec 带注释的方法 get:它包含一个针对超类型 case _ => tail.get(n-1) 的递归调用”。有人可以解释这是为什么吗?
trait List[T] {
def isEmpty: Boolean
def head: T
def tail: List[T]
def get(n: Int): T
}
class Cons[T](val head: T, val tail: List[T]) extends List[T]{
def isEmpty = false
@tailrec
final def get(n: Int) =
n match {
case 0 => head
case _ => tail.get(n-1)
}
}
class Nil[T] extends List[T]{
def isEmpty = true
def head = throw new NoSuchElementException("Nil.head")
def tail = throw new NoSuchElementException("Nil.tail")
final def get(n: Int): T = throw new IndexOutOfBoundsException
}
object Main extends App{
println(new Cons(4, new Cons(7, new Cons(13, new Nil))).get(3))
}