🔴 Scala Beginner

What is tail recursion in Scala?

Answer

Tail recursion is a form of recursion where the recursive call is the last operation in the function. The Scala compiler optimizes tail-recursive functions into loops (tail call elimination), preventing stack overflow for deep recursion. Mark a function with @tailrec annotation to get a compile error if the compiler can't optimize it: @tailrec def factorial(n: Int, acc: Int = 1): Int = if (n <= 1) acc else factorial(n - 1, n * acc). Without @tailrec, a non-tail-recursive factorial with large input would throw a StackOverflowError. The @tailrec annotation is a safety net — it ensures you've written the function in tail-recursive form. When Scala 2 cannot optimize, you can use a trampoline from the Scalaz/Cats library. Tail recursion is the functional programming alternative to while loops.