0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

The tailrec Annotation

Guaranteed optimization.

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.

All lessons in this course

  1. Recursion Basics
  2. The tailrec Annotation
  3. Accumulator Pattern
  4. Trampolining
← Back to Scala for Backend Engineering & Functional Programming