我完全同意 Petr Pudlák 的回答。但是对于它的价值,有一个出路:定义一个帮助方法来返回一个包装函数到tailrectest:
import scala.annotation.tailrec
object Test extends App {
def tailrectest_ = tailrectest _
@tailrec
def tailrectest(i: Int): Int = i match {
case i if i > 0 => {
val x = () => tailrectest_(10)
tailrectest(i - 1)
}
case 0 => 0
}
}
这给代码增加了一些噪音,但至少它有效。
但是,如果您要做的是构建某种延续,那么您的真实世界代码肯定必须在闭包中捕获一些本地上下文,这排除了我的上述解决方案。在这种情况下,我看不到一个简单的出路。
更新(2013 年 3 月 11 日):
Petr Pudlak found a similar but superior solution in another question: http://stackoverflow.com/questions/15334611/how-to-make-a-tail-recusive-method-that-can-also-refer-to-itself-in-a-non-tail-r
By using an inner function, we can actually capture local state, which make it fully usable. Here is his solution, applied to entropyslave's original question:
import scala.annotation.tailrec
object Test extends App {
def tailrectest(i: Int): Int = {
@tailrec
def tailrectestImpl(i: Int): Int = {
i match {
case i if i > 0 =>
val x = () => tailrectest(10)
tailrectestImpl(i - 1)
case 0 => 0
}
}
tailrectest( i )
}
}