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:
tailrecannotation: Kotlin requires an explicit@tailrecannotation for functions that should be optimized using tail recursion.- Compiler optimization: If a function is annotated as
tailrecand 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. - Transformation into a loop: The optimization involves transforming the recursive call into a regular
whileloop. This prevents stack growth and avoids stack overflow errors during deep recursion. - 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
}