Kotlin Recursive Function and Tail Recursion

 

 

 

 

 

 

  

 

1. Recursive Function

A function which calls itself is known as Recursive function and the call is known as Recursive call.
   

There can be two types of function calls


1. Normal function call

         //declaring a function
      fun add(a : Int, b : Int) : Int {
        a + b
      }
 
      //calling function
      add(2, 4)
 

2. Recursive function call
 

The best and most common example of a recursive function call is finding the factorial of a number.

      fun findFactorial(num : Int) : Int {
        return if (num == 1) 1
        else num * findFactorial(num - 1)
      }


What is Tail Recursion


When the recursive call is the last statement of the function it is known as tail recursion. Benefits of tail recursion :

1. When the function call is last statement of the function, there is nothing left for the compiler to execute, So there is no need to save the current function call in the stack memory.

2. In tail recursion we do not get StackOverFlow error in the program.


What is StackOverFlow error ?

When we call a method, a new stack frame is created on the call stack. This stack frame generally contains the arguments, local variables etc. When we keep calling the function, a state is reached when JVM runs out of space for new stack frames to be created and it throws StackOverFlow error.

Comments