Recursion in Scala

import scala.annotation.tailrec

// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
def fact(n: Int): Int = {
  if (n == 0) {
    1
  } else {
    n * fact(n - 1)
  }
}

@main def main(): Unit = {
  println(fact(7))

  // In Scala, we can define recursive functions directly
  // without needing to declare them separately.
  def fib(n: Int): Int = {
    if (n < 2) {
      n
    } else {
      fib(n - 1) + fib(n - 2)
    }
  }

  println(fib(7))
}

Scala supports recursive functions, similar to many other programming languages. Here’s a classic example demonstrating recursion.

The fact function is a recursive implementation of the factorial calculation. It calls itself with a decremented value until it reaches the base case of fact(0).

In the main function, we first call and print the result of fact(7).

Scala allows us to define recursive functions directly within other functions or methods. This is demonstrated with the fib function, which calculates the Fibonacci sequence recursively.

The fib function is defined within the main function. It checks if the input is less than 2 (base case) and returns the input if true. Otherwise, it recursively calls itself with n-1 and n-2, summing the results.

Finally, we call and print the result of fib(7).

To run this Scala program:

$ scala recursion.scala
5040
13

The output shows the factorial of 7 (5040) and the 7th number in the Fibonacci sequence (13).

Note: In Scala 3, we use the @main annotation to denote the entry point of our program, replacing the traditional object with main method approach used in earlier Scala versions.