Scala supports tail recursion, which sets it apart from other languages. Recursion involves breaking a problem down into smaller sub-problems and calling itself to resolve each of them. Simply put, recursion can be thought of as a function calling itself. Tail recursion refers to executing the last statement recursively. As a result, these functions are more performant since they utilize tail call optimization. They do not add another stack frame to memory, but rather keep calling functions. If you are experiencing a stack overflow with your recursive functions, a tail-recursive function is your remedy. In addition, tail recursion makes your code faster and memory-constant.
Syntax:
@tailrecdef FuntionName(Parameter1, Parameter2, ...): type = …
Example:
import scala.annotation.tailrec
object Madanswer
{
def SCALER(a: Int, b: Int): Int =
{
@tailrec def scaler(x:Int, y:Int): Int=
{
if (y == 0) x
else scaler(y, x % y)
}
scaler(a, b)
}
def main(args:Array[String])
{
println(SCALER(11, 7))
}
}
Output:
4