Tail Recursive loop

All of the above loop examples are imperative functions making use of iteration. Scala as a functional programming language supports Recursion (tail in this example) and Iteration (as above). Because Recursion will fail if there is a finite call stack, Java, for example, prefers Iteration which holds the local variables called by the function. As a result Java provides for loops, for-each loops, while loops, do loops, arrays, Iterators, ResultSets, etc.

Scala supports Tail Recursion that can use the same stack frame by encapsulating the loop. Once the loop has completed Scala does not need the local variables anymore because it has completed all the encapsulated computations. Scala can then reuse the exact same stack frame the next time it loops through the very same function. This limits Out of Memory exceptions and makes parallel processing easier.

Scala provides the @tailrec method annotation which verifies that the method will be compiled with tail call optimisation. If it is present, the compiler will issue an error if the method cannot be optimised into a loop.