應用@tailrec我從scala編譯器收到錯誤:「無法優化@tailrec註釋方法get:它包含一個遞歸調用,目標是一個超類case _ => tail.get第(n-1)」。有人能解釋爲什麼嗎?@tailrec錯誤「遞歸調用目標超類型」
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))
}
謝謝你,我知道了!你能解釋一下關於「列表T在T中協變」的說明嗎? – damluar
http://stackoverflow.com/questions/663254/scala-covariance-contravariance-question –