🏎️ · Tail-recursive functions

2 min read · Updated on by

Read on to find a brief summary of tail recursive functions and the tailrec keyword, trampolining and DeepRecursiveFunction.

As you get more and more versed in functional programming, you may find yourself writing (or wanting to write) recursive functions, i.e. functions that call themselves. A problem often associated with recursive functions is stack overflow, i.e. the function calling itself so many times that the stack runs out of space.

To help with that, Kotlin offers the tailrec keyword, which allows the compiler to take advantage of a form of recursion called tail recursion. When this form of recursion is used, the compiler can use tail-call optimization which prevents stack overflows from happening (although you can still get infinite loops).

You are encouraged to Google those terms and learn about them, they’re a useful tool to have in your belt. However, being proficient in tail recursion is not a prerequisite for being a Kotlin developer, so we won’t go into them here. Just keeps this vaguely in mind, and come back to it if you ever find yourself writing a lot of recursive functions.

While it is always possible to write recursive functions in tail-call form using certain techniques involving continuations, it’s often tedious to do so. Lucky for us, there are libraries that implement those techniques, and there’s even a standard library component implemented exactly for this purpose. However, we won’t go into detail, because it’s an advanced topic with a fairly narrow range of use-cases in the average enterprise application.

You can find out more about the keyword in the documentation.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer