Tail Recursion in Kotlin

Have you heard about the modifier keyword tailrec in Kotlin? Do you know the idea behind this interesting keyword and how it is used?

Lam Pham
The Startup

--

Recursive gates
Image by Tuan Hung Nguyen from Pixabay

In Kotlin, there are a bunch of modifier keywords that are very useful in some use cases. Some of them are already well-known because of their high applicability such as: inline, inner, lateinit, reified, open, override etc. In contrast, several ones are not largely known because there is not often use case that requires these features.

In this article, we will discover such a keyword: tailrec, and what it provides.

According to the official documentation:

tailrec marks a function as tail-recursive (allowing the compiler to replace recursion with iteration)

Following this definition, there must be something wrong with a recursive function since the compiler has to replace it with an iteration (for loop for instance).

So, what is wrong?

A recursion function will cause the stackOverflowError when the number of recursive-calls is significant enough.

Look at this function:

private fun factorial(n : Long) : Long {
return if (n == 1L) n
else n * factorial(n -1)
}

--

--