A function is said to be recursive when it calls itself. Recursion is a powerful tool, and it is often used in functional programming. It allows you to break complex problems into smaller subproblems, making them easier to reason through and solve. Recursion also works well with the idea of immutability. Recursive functions provide us with a good way to manage changing state without using mutable structures or reassignable variables. In this section, we focus on the different shortcomings of using recursion on the JVM, and especially in Scala.
Let's take a look at a simple example of a recursive method. The following snippet shows a sum
method that is used to calculate the sum of a list of integers:
def sum(l: List[Int]): Int = l match { case Nil => 0 case x :: xs => x + sum(xs) }
The sum
method presented in the preceding code snippet performs what is called head-recursion. The sum(xs)
recursive call is not the last instruction in the function...