Android ● ● ● Kotlin 2.0

Kodebits Day 99: Tail Recursion

Sep 28 2026
Practice recursion with a short kotlin challenge.

What does this print?

tailrec fun rev(
  s: String,
  acc: String = ""
): String {
  return if (s.isEmpty()) acc
  else rev(s.drop(1), s[0] + acc)
}
fun main() {
  println(rev("code"))
}

[spoiler title="Solution"]

Answer:

edoc

Explanation:

tailrec optimizes tail-recursive calls into loops, preventing stack overflow. Here, each character is prepended to the accumulator while dropping from the original string.

[/spoiler]


Further Reading