fre*_*low 0 eclipse recursion scala tail-recursion pattern-matching
这是一个演示我的问题的最小例子:
@tailrec
def fun(x: Int): Int = {
val y = x match {
case 5 => return fun(6)
case 7 => return fun(6)
case 6 => 40
case _ => throw new AssertionError("only 5, 6 and 7 allowed")
}
y + 2
}
Run Code Online (Sandbox Code Playgroud)
Eclipse抱怨以下错误消息:
could not optimize @tailrec annotated method
it contains a recursive call not in tail position
Run Code Online (Sandbox Code Playgroud)
由于return关键字,有两个递归调用,就我所知,在尾部位置.
Eclipse究竟抱怨什么?我只是没有看到它.
return 导致它不是尾调用.
请改用以下内容:
@tailrec
def fun(x: Int): Int = x match {
case 5 => fun(6)
case 7 => fun(6)
case 6 => 42
case _ => throw new AssertionError("only 5, 6 and 7 allowed")
}
Run Code Online (Sandbox Code Playgroud)
这可能是一个实现错误,也可能与return x编译代码的可能性有关,该代码NonLocalReturnControl在检查的编译阶段之后抛出异常tailrec.