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:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

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

Update cookies preferences