In a recent StackOverflow answer, I gave the following recursive code:
def retry[T](n: Int)(fn: => T): T = {
try {
fn
} catch {
case e if n > 1 =>
retry(n - 1)(fn)
}
}
If I add the @tailrec
annotation, I get:
Could not optimize @tailrec annotated method retry: it contains a recursive call not in tail position.
I was able to hack a tail-recursive alternative, but I still wonder why this didn't optimize. Why not?