Recursion in Scala
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:
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.