0Pricing
Kotlin Academy · Lesson

tailrec Functions

Optimize recursion.

What Is Tail Recursion?

A function is tail-recursive when its recursive call is the very last operation. Kotlin can then optimize it into a loop, avoiding stack overflow.

tailrec fun countdown(n: Int) {
    if (n < 0) return
    println(n)
    countdown(n - 1)
}

fun main() {
    countdown(3)
}

The tailrec Modifier

Add the tailrec modifier and the compiler rewrites the recursion as iteration, using constant stack space.

tailrec fun sum(n: Int, acc: Int = 0): Int {
    if (n == 0) return acc
    return sum(n - 1, acc + n)
}

fun main() {
    println(sum(100))
}

All lessons in this course

  1. Infix Functions
  2. Building DSL-like APIs
  3. tailrec Functions
  4. When to Use Each
← Back to Kotlin Academy