Sobes.tech
Junior — Middle

Is it possible to apply the inline keyword together with tailrec for recursive functions in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the keyword tailrec is used to optimize tail recursion, allowing the compiler to transform a recursive call into a loop and avoid stack overflow. The keyword inline, on the other hand, forces the compiler to insert the function body directly at the call site to reduce overhead.

However, inline cannot be used together with tailrec. This is because tailrec requires the function to be a regular function that can be transformed into a loop, while inline changes the way the function is called, which conflicts with tail recursion optimization.

Attempting to declare a function with both modifiers will result in a compiler error.

Example of incorrect usage:

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

The correct approach is to use only tailrec for recursive functions that require tail recursion optimization.