fredoverflow
fredoverflow

Reputation: 263078

@tailrec annotated method contains a recursive call not in tail position

Here is an minimal example that demonstrates my problem:

@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
}

Eclipse complains with the following error message:

could not optimize @tailrec annotated method
it contains a recursive call not in tail position

There are two recursive calls, both in tail position, as far as I can tell, due to the return keyword.

What exactly is Eclipse complaining about? I just don't see it.

Upvotes: 0

Views: 567

Answers (1)

user1804599
user1804599

Reputation:

return causes it not to be a tail call.

Use the following instead:

@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")
}

This is either an implementation bug or has to do with the possibility of return x compiling to code that throws a NonLocalReturnControl exception in a compilation phase that comes after the one that checks for tailrec.

Upvotes: 6

Related Questions