Kotlin Recursion FunctionRecursion function is a function which calls itself continuously. This technique is called recursion. Syntax Kotlin recursion function example 1: Finite timesLet's see an example of recursion function printing count. Output: hello 1 hello 2 hello 3 hello 4 hello 5 Kotlin recursion function example 2: Factorial NumberLet's see an example of recursion function calculating factorial of number. Output: Factorial of 5 = 120 Working process of above factorial example Kotlin Tail RecursionBefore 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. General RecursionLet's see an example of calculating sum of nth (100000 larger number) using general (normal) recursion. Output: 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 RecursionTail 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) numberLet's see an example of calculating sum of nth (100000 larger number) using tail recursion. Output: sun of upto 100000 number = 5000050000 Kotlin Tail Recursion Example 2: calculating factorial of numberLet's see an example of calculating factorial of number using tail recursion. Output: Factorial of 4 = 24
Next TopicKotlin Default and Named Argument
|