Trampolining
Stack-safe recursion.
The Limit of @tailrec
@tailrec only optimizes a function calling itself directly. It cannot help with mutual recursion (two functions calling each other), which still grows the stack. Trampolining solves this.
The Mutual Recursion Problem
Consider isEven and isOdd defined in terms of each other. For a large number this overflows the stack, and neither can be marked @tailrec.
object Main {
def isEven(n: Int): Boolean = if (n == 0) true else isOdd(n - 1)
def isOdd(n: Int): Boolean = if (n == 0) false else isEven(n - 1)
def main(args: Array[String]): Unit = {
println(isEven(10))
}
}