Kotlin Recursion Functions: Loop Back in 2025

A recursion function calls itself repeatedly—a clever loop-in-a-loop technique! 🌟

Two Flavors:

  • 🔄 Standard Recursion: Calls itself until a base case stops it.
  • 🌀 Tail Recursion: Calculates first, then recurses—optimized for efficiency.

Standard Recursion 🔄

A function that keeps calling itself until it hits a base condition.

Example: Factorial using recursion:

fun main(args: Array<String>) {
val number = 4
val result = factorial(number)
println("Factorial of $number = $result") // Outputs: Factorial of 4 = 24
}
fun factorial(n: Int): Long {
return if (n == 1) n.toLong() else n * factorial(n - 1)
}

How It Works:

factorial(4)              // 1st call: 4
4 * factorial(3) // 2nd call: 3
4 * (3 * factorial(2)) // 3rd call: 2
4 * (3 * (2 * factorial(1))) // 4th call: 1
4 * (3 * (2 * 1)) // Resolves: 24

Recursion Notes:

  • 🔄 Builds a call stack—can overflow if too deep.
  • ⚡ Simple but memory-intensive.

Tail Recursion 🌀

Tail recursion computes first, then recurses—passing results along. The recursive call must be the last operation.

Use the tailrec modifier to optimize it—no stack growth!

fun main(args: Array<String>) {
val number = 4
val result = factorial(number)
println("Factorial of $number = $result") // Outputs: Factorial of 4 = 24
}
tailrec fun factorial(n: Int, run: Int = 1): Long {
return if (n == 1) run.toLong() else factorial(n - 1, run * n)
}

How It Works:

  • 🌀 factorial(4, 1)factorial(3, 4)factorial(2, 12)factorial(1, 24) → 24.
  • ⚡ Accumulates in run, recurses last—no stack buildup!

Tailrec Benefits:

  • 🚀 Optimized—compiler turns it into a loop.
  • 🔧 Safer for large inputs—no stack overflow.

Quick Comparison Table 🤔

A snapshot of recursion types in Kotlin:

Recursion Type Execution Order Key Features Best Use Case
Standard Recurses first, computes later Builds call stack, simple Small, straightforward tasks
Tail Computes first, recurses last No stack growth with tailrec Large inputs, performance

Table Notes:

  • 🔍 Execution Order: When computation vs. recursion happens.
  • Key Features: What sets it apart.
  • Best Use Case: Ideal scenario for each.

..

Comments

Popular posts from this blog

Creating Beautiful Card UI in Flutter

Jetpack Compose - Card View