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
- Infix Functions
- Building DSL-like APIs
- tailrec Functions
- When to Use Each