How to Use Recursion in Kotlin: Simple Guide with Examples
In Kotlin, recursion is when a function calls itself to solve smaller parts of a problem. You define a
fun that calls itself with a changed argument until it reaches a base case to stop the calls.Syntax
Recursion in Kotlin uses a function that calls itself. It must have a base case to stop calling itself, or it will run forever. The function usually processes input and calls itself with a smaller or simpler input.
fun: declares the function- Function name: any valid name
- Parameters: input values to process
- Return type: type of result
- Base case: condition to stop recursion
- Recursive call: function calls itself with new arguments
kotlin
fun recursiveFunction(param: Int): Int {
if (param <= 0) return 0 // base case
return param + recursiveFunction(param - 1) // recursive call
}Example
This example shows a recursive function that calculates the factorial of a number. Factorial means multiplying the number by all smaller positive numbers down to 1.
kotlin
fun factorial(n: Int): Int {
if (n <= 1) return 1 // base case
return n * factorial(n - 1) // recursive call
}
fun main() {
println(factorial(5)) // Output: 120
}Output
120
Common Pitfalls
Common mistakes when using recursion include:
- Missing or incorrect base case, causing infinite recursion and crash.
- Not reducing the problem size in recursive calls, so it never reaches the base case.
- Stack overflow errors if recursion is too deep without optimization.
Always ensure your base case is reachable and your recursive call moves toward it.
kotlin
/* Wrong: No base case, causes infinite recursion */ fun wrongRecursion(n: Int): Int { return n + wrongRecursion(n - 1) } /* Correct: Has base case to stop recursion */ fun correctRecursion(n: Int): Int { if (n <= 0) return 0 return n + correctRecursion(n - 1) }
Quick Reference
Tips for using recursion in Kotlin:
- Always define a clear base case to stop recursion.
- Make sure each recursive call simplifies the problem.
- Use recursion for problems like factorial, Fibonacci, tree traversal.
- For deep recursion, consider iterative solutions or Kotlin's
tailrecmodifier for optimization.
Key Takeaways
Recursion is a function calling itself with simpler input until a base case stops it.
Always include a base case to avoid infinite loops and crashes.
Each recursive call must move closer to the base case.
Use recursion for problems that break down naturally into smaller parts.
Consider Kotlin's tailrec modifier to optimize recursive functions.