问题
@tailrec
private def loop[V](key: String): V = {
key match {
case _ => loop(key)
}
}
This method doesn't compile and complains that it 'contains a recursive call not in tail position'. Can someone explain to me what's going on? This error message doesn't make sense to me.
回答1:
It compiles ok if the generic type is specified:
import scala.annotation.tailrec
@tailrec
private def loop[V](key: String): V = {
key match {
case _ => loop[V](key)
}
}
I think the error message is misleading in this case.
A simplified version gives a better hint on what's going on:
scala> @tailrec
| private def loop[V](key: String): V = {
| loop(key)
| }
<console>:14: error: could not optimize @tailrec annotated method loop: it is called recursively with different type arguments
loop(key)
^
来源:https://stackoverflow.com/questions/45358283/tailrec-why-does-this-method-not-compile-with-contains-a-recursive-call-not-in