The tailrec Annotation
Guaranteed optimization.
The tailrec Annotation is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What is Tail Recursion?
A recursive call is in tail position when it is the very last action of the function. A tail-recursive function can be optimized into a loop, reusing a single stack frame, so it never overflows.
Tail Position
In n * factorial(n-1), the recursive call is not last: the multiplication happens after it returns. In gcd(b, a % b), the call is last. Only the latter is tail-recursive.
The @tailrec Annotation
Import scala.annotation.tailrec and annotate a method. The compiler then verifies the call is truly in tail position and applies the optimization. If it is not, compilation fails.
import scala.annotation.tailrec
object Main {
@tailrec
def countdown(n: Int): Unit = {
if (n >= 0) {
println(n)
countdown(n - 1)
}
}
def main(args: Array[String]): Unit = countdown(3)
}Guaranteed Optimization
The key benefit of @tailrec is the compile-time guarantee. You are told immediately if your function is not stack-safe, rather than discovering it via a runtime crash on large input.
A Tail-Recursive gcd
Euclid's algorithm is already tail-recursive: the recursive call is the entire body's result. Annotating it confirms this.
import scala.annotation.tailrec
object Main {
@tailrec
def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
def main(args: Array[String]): Unit = {
println(gcd(1071, 462))
}
}What Breaks Tail Position
Common patterns that move the call out of tail position:
- Doing arithmetic on the result:
n + f(...). - Wrapping in a constructor:
x :: f(...). - Using the result in a
tryblock.
Non-Tail Example
This sum is not tail-recursive because the addition wraps the call. Annotating it with @tailrec would cause a compile error. (Shown without the annotation so it runs.)
object Main {
def sum(n: Int): Int =
if (n == 0) 0
else n + sum(n - 1)
def main(args: Array[String]): Unit = {
println(sum(100))
}
}Why It Cannot Be Optimized
Because n + sum(n - 1) must remember n to finish the addition after the call returns, each level needs its own stack frame. The compiler cannot collapse this into a loop, so it is not tail-recursive.
A Large Tail-Recursive Loop
A tail-recursive sum using an accumulator runs for huge inputs without overflowing, because it reuses one frame.
import scala.annotation.tailrec
object Main {
@tailrec
def sumTo(n: Int, acc: Long = 0): Long =
if (n == 0) acc else sumTo(n - 1, acc + n)
def main(args: Array[String]): Unit = {
println(sumTo(1000000))
}
}tailrec Requires final or Local
For @tailrec to apply, the method must not be overridable: it must be private, final, or a local/nested method. An open method could be overridden, breaking the optimization, so the compiler rejects it.
Mutual Recursion Caveat
@tailrec only optimizes a function calling itself. Two functions calling each other (mutual recursion) cannot be tail-optimized by the JVM directly; for that you need trampolining, covered later.
Quick Check
Test your understanding of @tailrec.
Recap
You learned the @tailrec annotation:
- A call in tail position can be optimized into a loop.
@tailrecgives a compile-time guarantee of stack safety.- The method must be
final,private, or local. - It only covers self-recursion, not mutual recursion.
Frequently asked questions
Is the “The tailrec Annotation” lesson free?
Yes — the full text of “The tailrec Annotation” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “The tailrec Annotation”?
Guaranteed optimization. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The tailrec Annotation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Recursion Basics
- The tailrec Annotation
- Accumulator Pattern
- Trampolining