
Recursion
Recursion is a function's call to itself. In simple words, a recursive function is a function which calls itself. Functional programming recommends use of recursion over the use of iterative looping constructs. For the same obvious reasons, Scala also recommends use of recursion. Let's first take a look at a recursive function:
object RecursionEx extends App {
/*
* 2 to the power n
* only works for positive integers!
*/
def power2toN(n: Int): Int = if(n == 0) 1 else 2 * power2toN(n - 1)
println(power2toN(2))
println(power2toN(4))
println(power2toN(6))
}
The following is the result:
4
16
64
We've defined a function power2toN which expects an integer n, checks for n value and if it's not 0, the function calls itself, decrementing n integer's value till the number n becomes 0. Then comes multiplying the value with 2 with each recursive call to get the desired result.
Consider the following:
def power2toN(n: Int) = if(n == 0) 1 else (2 * power2toN(n - 1))
The Scala compiler gives an error stating Recursive method power2N needs result type. This is a required condition by the Scala compiler. We have to explicitly define the response type of a recursive function—that's the reason we have to give the return type with the method definition.