Tail Recursive Function in Scala PRO

If the last action a function performs is calling to itself then it is a tail recursive function. When a tail recursive function is executed the computer doesn’t need to keep the memory stack frames. It can use one frame only. Using the @tailrec annotation we can instruct the computer to use one frame only and avoid keeping the stack frames. Doing so we improve the performance of our code.

import annotation.tailrec

object Program
{
  def main(args: Array[String]):Unit =
  {
    println(factorial(4))
  }

  def factorial(num:Int):Int =
  {
    @tailrec
    def calculate(accumulator:Int,number:Int):Int =
    {
      if(number==0)
        accumulator
      else
        calculate(accumulator*number,number-1)
    }
    calculate(1,num)
  }
}

The following video clip goes over this code sample, shows its execution and explains it.

Share:

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences