A anotação tailrec
Otimização garantida.
A anotação tailrec é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “A anotação tailrec” é grátis?
Sim — o texto completo de “A anotação tailrec” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
O que vou aprender em “A anotação tailrec”?
Otimização garantida. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?
Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “A anotação tailrec”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?
Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Fundamentos da recursão
- A anotação tailrec
- Padrão acumulador
- Trampolim