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 Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

What are Anti Patterns?

Anti Patterns

Unlike design patterns, anti patterns just seem to be a solution. However, they are not a solution and they cause additional costs.

Virtual Threads in Java Professional Seminar

Virtual Threads in Java

The use of virtual threads can assist us with improving the performance of our code. Learn how to use virtual threads effectively.

The Beauty of Code

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

Update cookies preferences