Kotlin Recursion Function
Recursion function is a function which calls itself continuously. This technique is called recursion.
Kotlin recursion function example 1: Finite times
Let's see an example of recursion function printing count.
hello 1 hello 2 hello 3 hello 4 hello 5
Kotlin recursion function example 2: Factorial Number
Let's see an example of recursion function calculating factorial of number.
Factorial of 5 = 120
Working process of above factorial example
Kotlin Tail Recursion
Before we will discuss about the tail recursion, let's try to make an example which calculate sum of nth (100000 larger number) using general (normal) recursion.
Let's see an example of calculating sum of nth (100000 larger number) using general (normal) recursion.
Exception in thread "main" java.lang.StackOverflowError
The above example throws an exception of "java.lang.StackOverflowError". This is because the compiler is unable to call large number of recursive function call.
Tail recursion is a recursion which performs the calculation first, then makes the recursive call. The result of current step is passed into the next recursive call.
Tail recursion follows one rule for implementation. This rule is as follow:
The recursive call must be the last call of the method. To declare a recursion as tail recursion we need to use tailrec modifier before the recursive function.
Kotlin Tail Recursion Example 1: calculating sun of nth(100000) number
Let's see an example of calculating sum of nth (100000 larger number) using tail recursion.
sun of upto 100000 number = 5000050000
Kotlin Tail Recursion Example 2: calculating factorial of number
Let's see an example of calculating factorial of number using tail recursion.
Factorial of 4 = 24