🐦 Kotlin Advanced

What is the tailrec modifier in Kotlin?

Answer

The tailrec modifier allows the compiler to optimize a tail-recursive function into an iterative loop, preventing stack overflow for deeply recursive calls. A tail-recursive function is one where the recursive call is the very last operation — there is no additional computation after the call. Example: tailrec fun factorial(n: Long, acc: Long = 1): Long = if (n == 1L) acc else factorial(n - 1, n * acc). Without tailrec, deep recursion would throw a StackOverflowError. The compiler generates a warning if you mark a function with tailrec but it is not actually tail-recursive.