Middle
What is a tail recursive function in Kotlin?
sobes.tech AI
Answer from AI
A tail recursive function in Kotlin is a recursive function where the recursive call is the last operation in the function body. This allows the compiler to optimize the calls by transforming recursion into a loop, preventing stack overflow.
To denote such a function, the tailrec modifier is used. If the function does not meet the tail recursion requirements, the compiler will produce an error.
An example of tail recursion for calculating factorial:
tailrec fun factorial(n: Int, acc: Int = 1): Int {
return if (n <= 1) acc else factorial(n - 1, acc * n)
}
Here, the recursive call factorial(n - 1, acc * n) is the last operation in the function, which allows for optimization.