0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Thinking Recursively

Base cases and recursive steps.

What Recursion Means

Recursion is when a function calls itself to solve a smaller version of the same problem.

In Scala, recursion is a natural fit for functional programming because it lets you express loops without mutable variables.

Every recursive function needs two things: a way to stop, and a way to shrink the problem.

Base Case First

The base case is the simplest input the function can answer directly, with no further recursion.

Without a base case, the function would call itself forever and crash with a stack overflow.

Always design the base case before the recursive step.

def countdown(n: Int): Unit =
  if (n < 0) ()           // base case: stop
  else {
    println(n)
    countdown(n - 1)      // recursive step
  }

All lessons in this course

  1. Thinking Recursively
  2. Accumulator Patterns
  3. foldLeft and foldRight
  4. reduce and aggregate
← Back to Scala for Backend Engineering & Functional Programming