0
0
KotlinConceptBeginner · 3 min read

What is tailrec in Kotlin: Explanation and Example

tailrec is a keyword in Kotlin that marks a function as tail-recursive, allowing the compiler to optimize recursive calls to avoid stack overflow. It means the function calls itself as its last operation, enabling the compiler to reuse the current stack frame.
⚙️

How It Works

Imagine you have a task that repeats itself, like climbing stairs one step at a time. Normally, each step you take adds a new layer to your memory (stack). If you climb too many steps, you might run out of memory. tailrec helps by allowing you to climb stairs without adding new layers for each step.

In programming, this means if a function calls itself as the very last action (tail call), Kotlin can optimize it by reusing the current function's memory instead of creating a new one. This optimization prevents the program from crashing due to too many recursive calls.

The compiler checks if the recursive call is in the tail position. If yes, it transforms the recursion into a loop behind the scenes, making it safe and efficient.

💻

Example

This example shows a tail-recursive function that calculates the factorial of a number. The tailrec keyword tells Kotlin to optimize the recursion.

kotlin
tailrec fun factorial(n: Int, acc: Int = 1): Int {
    return if (n <= 1) acc else factorial(n - 1, n * acc)
}

fun main() {
    println(factorial(5))
}
Output
120
🎯

When to Use

Use tailrec when you have a recursive function that can be written so the recursive call is the last operation. This is common in mathematical calculations like factorial, Fibonacci, or traversing data structures.

It is especially useful when dealing with large inputs where normal recursion would cause a stack overflow error. By using tailrec, you make your recursive functions safe and efficient, similar to loops but with clearer, more natural code.

Key Points

  • tailrec enables compiler optimization of recursive functions.
  • The recursive call must be the last action in the function.
  • It prevents stack overflow by reusing the current stack frame.
  • Useful for large input recursive problems like factorial or Fibonacci.
  • Improves performance and safety of recursion.

Key Takeaways

tailrec marks a function for tail call optimization to avoid stack overflow.
The recursive call must be the last operation in the function to use tailrec.
Kotlin transforms tail-recursive calls into loops behind the scenes for efficiency.
Use tailrec for safe recursion with large inputs like factorial calculations.
It improves performance and prevents crashes from deep recursion.