Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 12 / 68

Recursive Functions

In this lesson you will learn how to write a recursive function in Kotlin and understand how a function can call itself. This is for anyone searching for "Kotlin recursive function how to use".

A recursive function is a function that calls itself. It suits work that repeats the same calculation pattern, such as "n! = n x (n-1)!".

The sample code has factorial call itself as n * factorial(n - 1) to compute the factorial of 5. The stopping condition if (n <= 1) return 1 is what makes the chain of calls come to an end.

A common stumbling block for beginners is forgetting that stopping condition. Without one, the function calls itself forever and the program crashes.

In real-world development, deep recursion consumes a lot of stack, so it is worth considering whether a loop would do instead.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)