Sobes.tech
Middle

What is a tail-recursive function and how does it work in Kotlin?

sobes.tech AI

Answer from AI

A tail-recursive function is a function where the recursive call is the last action before returning a value.

Features and working principle in Kotlin:

  1. tailrec annotation: Kotlin requires an explicit @tailrec annotation for functions that should be optimized using tail recursion.
  2. Compiler optimization: If a function is annotated as tailrec and meets the tail recursion criteria (recursive call is the last action, and the result of the call is not used in other computations), the compiler optimizes it.
  3. Transformation into a loop: The optimization involves transforming the recursive call into a regular while loop. This prevents stack growth and avoids stack overflow errors during deep recursion.
  4. Prevention of StackOverflowError: The main advantage is the ability to work efficiently with deep recursive calls without risking a StackOverflowError.

Example:

// Non-optimized recursion - may cause StackOverflowError for large N
fun factorialRecursive(n: Long): Long {
    return if (n <= 1) 1 else n * factorialRecursive(n - 1)
}

// Tail-recursive function
tailrec fun factorialTailrec(n: Long, accumulator: Long = 1): Long {
    return if (n <= 1) accumulator else factorialTailrec(n - 1, n * accumulator)
}

fun main() {
    println(factorialTailrec(5)) // Outputs 120
}
What is a tail-recursive function and how does it… - sobes.tech