Signup/Sign In
LAST UPDATED: AUGUST 5, 2020

Kotlin Recursive Functions

In this tutorial we will discuss about Kotlin recursive functions. A function in Kotlin which calls itself continuously is known as recursive function. This concept is not native to Kotlin but is present in all the languages. Recursive function can be considered as a loop but both are not completely same.

The recursive function must have a breaking condition to stop the recursion; else it will run indefinitely. Mostly the breaking condition is based on a parameter passed to the function.

The basic syntax of recursive function is:

fun sayBye(){
   sayBye()
}

When a function is called inside itself: This makes a function recursive.

Let us write a program to find factorial of a number. We will first write it using for loop and then later using recursive function.

Here is the implementation using the for loop:

fun main() {
    println("Factorial of 5 is: ${factorial(5)}")
}
fun factorial(n: Int): Int{
    var factorialOfN = 1
    for(i in n downTo 1){
        factorialOfN *= i
    }
    return factorialOfN
}


Factorial of 5 is: 120

Now let's implement this using Recursive function:

fun main() {
    println("Factorial of 5 is: ${factorial(5)}")
}
fun factorial(n: Int): Int{
    if(n == 1)
        return 1
    return n * factorial(n - 1)
}

It will also produce the same output.

Explanation:

  1. First, factorial(5) is called from main() function.

  2. Inside factorial(5) the condition is checked and value returned is 5 * factorial(4).

  3. Now, factorial(4) is called and it will return 4 * factorial(3).

  4. Next, factorial(3) is called and it will return 3 * factorial(2).

  5. Similarly, factorial(2) is called and it will return 2 * factorial(1) .

  6. At last, factorial(1) will return 1 by checking the if condition and the recursion ends here.

  7. The value obtained from step 6 will be returned to step 5 i.e. 2 * factorial(1) will become 2 *1.

  8. Similarly these values are returned at each step and at last the value return to the main function will be 5*4*3*2*1.

Summary

In this tutorial we discussed about recursive functions in general and how we implement the same in Kotlin. You can search more about recursive functions and their usages. In the next tutorial we will discuss about types of arguments in Kotlin.



About the author:
I'm a writer at studytonight.com.