Kotlin recursion functions example

Published by inkskull on

Checkout the kotlin recursion functions


Kotlin is a general-purpose, statically typed, and open-source programming language. It runs on JVM and can be used anywhere Java is used today. It can be used to develop Android apps, server-side apps and much more. Google accepetd the kotlin as the officill language for android.


Kotlin was developed by JetBrains team. A project was started in 2010 to develop the language and officially, first released in February 2016. Kotlin was developed under the Apache 2.0 license.


  • Concise: Kotlin reduces writing the extra codes. This makes Kotlin more concise.
  • Null safety: Kotlin is null safety language. Kotlin aimed to eliminate the NullPointerException (null reference) from the code.Interoperable.
  • Interoperable: Kotlin easily calls the Java code in a natural way as well as Kotlin code can be used by Java.
  • Smart cast: It explicitly typecasts the immutable values and inserts the value in its safe cast automatically.
  • Compilation Time: It has better performance and fast compilation time.
  • Tool-friendly: Kotlin programs are build using the command line as well as any of Java IDE.
  • Extension function: Kotlin supports extension functions and extension properties which means it helps to extend the functionality of classes without touching their code.


Recursion function is a function which calls itself continuously. This technique is called recursion.


  1. fun functionName(){
  2. .. .. ..
  3. functionName() //calling same function
  4. }

Tail Recursion

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.

  1. fun main(args: Array<String>) {
  2. var number = 100000.toLong()
  3. var result = recursiveSum(number)
  4. println(“sun of upto $number number = $result”)
  5. }
  6. tailrec fun recursiveSum(n: Long, semiresult: Long = 0) : Long {
  7. return if (n <= 0) {
  8. semiresult
  9. } else {
  10. recursiveSum( (n – 1), n+semiresult)
  11. }
  12. }


Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By : XYZScripts.com