← Back to Scala Course | Chapter 5: Functions | Lesson 7 of 7

Recursive Functions

A recursive function solves a problem by calling itself on a smaller version, like opening Russian dolls until you reach the tiniest one. It needs a stopping point so it does not go on forever.

In this page:

  1. Recursive Functions
Syntax
scala
def function_name(n: Int): Int = {
  if (n <= 1) base_value    // base case
  else n * function_name(n - 1)    // recursive step
}

Recursive Functions

A Scala function can call itself, producing recursion, as long as there's a base case that stops it. Recursive functions need an explicit return type annotation (unlike simple functions where it can often be inferred), since the compiler can't infer a recursive function's return type from its own body.

The @tailrec annotation can be added to verify, at compile time, that a recursive call is in tail position and will be optimized into a loop instead of growing the call stack.

Warning: A recursive function's return type must be explicitly declared -- Scala cannot infer it from a body that calls the function itself.

Example: Recursive Functions

markup
object Main extends App {
  def factorial(n: Int): Int = {
    if (n <= 1) 1
    else n * factorial(n - 1)
  }

  println(factorial(5))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving out the base case, so factorial calls itself forever and ends in a StackOverflowError.
  2. Using Int for factorial(20), which overflows silently and gives a wrong number; use Long or BigInt.
  3. Forgetting that recursion needs a declared return type, so def factorial(n: Int) = ... gives an error.
Chapter Summary
  • Functions have parameters and return types, and can use default parameters, named arguments, and varargs.
  • Nested functions keep helpers local.
  • Recursive functions call themselves to solve problems.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.