0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Trampolining

Stack-safe recursion.

The Limit of @tailrec

@tailrec only optimizes a function calling itself directly. It cannot help with mutual recursion (two functions calling each other), which still grows the stack. Trampolining solves this.

The Mutual Recursion Problem

Consider isEven and isOdd defined in terms of each other. For a large number this overflows the stack, and neither can be marked @tailrec.

object Main {
  def isEven(n: Int): Boolean = if (n == 0) true else isOdd(n - 1)
  def isOdd(n: Int): Boolean  = if (n == 0) false else isEven(n - 1)

  def main(args: Array[String]): Unit = {
    println(isEven(10))
  }
}

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