Kotlin

tailrec — Tail-Call Optimization

admin by @admin ADMIN
Jun 16, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Mark a recursive function `tailrec` and the compiler rewrites it as a loop — no stack frame per call, no StackOverflowError on deep recursion. Function must end with itself as the FINAL expression.
Kotlin
Raw
// Without tailrec — deep recursion blows the stack
fun factorial(n: Long, acc: Long = 1): Long =
    if (n <= 1) acc else factorial(n - 1, acc * n)

// With tailrec — compiler emits a loop, no stack growth
tailrec fun factorialSafe(n: Long, acc: Long = 1): Long =
    if (n <= 1) acc else factorialSafe(n - 1, acc * n)

// Classic — list iteration
tailrec fun <T> findLast(list: List<T>, index: Int = 0): T? = when {
    list.isEmpty()            -> null
    index == list.lastIndex   -> list[index]
    else                      -> findLast(list, index + 1)
}

fun main() {
    println(factorialSafe(20))                          // 2432902008176640000

    // Without tailrec, factorial(100_000) would StackOverflow.
    println(factorialSafe(100_000) > 0)                 // true (BigInt-style overflow but no SOE)

    println(findLast(listOf("a", "b", "c", "d")))       // d
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.