What is a recursive method?
A method that calls itself many times before reaching a specific condition or
What is a tail-recursive method?
A method which calls itself in the last instruction (
). In the case of Scala (and other FP languages), a
method can reuse the stack frames in each iteration.
We can specify that a method has to be tail-recursive using the annotation
(if the implementation isn’t tail-recursive, the compiler shows an error).
In the following example, the tail-recursive method returns the last element of a list of Integers given by parameter:
If the given
matches with a List of one element (
) the method responds with that element,
In other case, if the
matches with a List of many elements composed by a head
and a tail
, the method calls itself passing the tail by parameter.
What is this strategy good for?
The depth of the JVM call stack is limited; for this reason, if we have deep recursive calls it’s a good idea to use a method tail-recursive to reuse stack frames and avoid stack overflow errors.
On the other hand, if we don’t have the case mentioned before, it’s better not to use a recursive tail method and leave the code more easy to read.
goto Part III