Recursive Functions
In this page:
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
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: