What is 'Tail Recursion' and how does Scala optimize it?
Instruction: Explain the concept of 'Tail Recursion' and how Scala's compiler deals with it.
Updated
A recursive call is in tail position when its result is returned directly, with no work remaining after the call. Scala can transform eligible direct self-recursion into a loop, avoiding a growing stack for those calls. @tailrec verifies that the transformation is possible; it does not enable an optimization that otherwise requires the annotation.
import scala.annotation.tailrec
def sum(values: List[Long]): Long = {
@tailrec
def loop(rest: List[Long], total: Long): Long = rest match {
case Nil => total
case head :: tail => loop(tail, total + head)
}
loop(values, 0L)
}
@main def tailRecursionExample(): Unit = {
assert(sum(Nil) == 0L)
assert(sum(List(1L, 2L, 3L)) == 6L)
assert(sum(List.fill(100000)(1L)) == 100000L)
}
Writing head + loop(tail, total) would leave addition after the recursive call and fail the annotation check. The local helper is not overridable; eligible methods must allow the compiler to safely replace their self-call. Do not assume general mutual recursion or calls through arbitrary function values receive this transformation. Tail-recursion annotation
Constant stack usage does not mean constant total memory or unlimited practical execution. The list and other intermediate data still occupy memory, and this Long sum can overflow. Choose checked arithmetic or arbitrary precision if the domain requires it, and measure the actual workload before making a speed claim.