Recursive Functions
In this page:
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.
Example: Recursive Functions
object Main extends App {
def factorial(n: Int): Int = {
if (n <= 1) 1
else n * factorial(n - 1)
}
println(factorial(5))
}
Login to try C/C++/Java/PHP code in the editor
- Leaving out the base case, so
factorialcalls itself forever and ends in aStackOverflowError. - Using
Intforfactorial(20), which overflows silently and gives a wrong number; useLongorBigInt. - Forgetting that recursion needs a declared return type, so
def factorial(n: Int) = ...gives an error.
- 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: