Left Index

Kotlin Recursion

Recursion is the process of repeating items in a self-similar way. If a program allows you to call a function inside the same function, then it is called a recursive call of the function. Recursion function is a function which calls itself continuously. This technique is called recursion. Syntax of recursion:

fun callMe() {
	// your bussiness logic

For understanding recursion, we create a method which will calculate factorial of given number, so let's see

package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var num = 5
	println("Factorial of ${num}: " + factorial(num))

fun factorial(num: Int): Int {
	if(num <= 0) {
		return 1;
	return num * factorial(num - 1);

In above example factorial() call itself and calculate factorial of given number, Output of above program is:

Factorial of 5: 120