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

Recursive Functions

In this page:

  1. Recursive Functions

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))
}
🔒

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.