Recursion in Kotlin
Kotlin supports recursive functions. Here’s a classic example.
import kotlin.math.pow
// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
fun fact(n: Int): Int {
return if (n == 0) {
1
} else {
n * fact(n - 1)
}
}
fun main() {
println(fact(7))
// In Kotlin, we can define local functions which can also be recursive
fun fib(n: Int): Int {
return if (n < 2) {
n
} else {
fib(n - 1) + fib(n - 2)
}
}
println(fib(7))
}
This program demonstrates two recursive functions:
- The
fact
function, which calculates the factorial of a number. - The
fib
function, which calculates the nth Fibonacci number.
Both functions use recursion, calling themselves with smaller inputs until they reach a base case.
In Kotlin, we can define local functions within other functions. This is demonstrated with the fib
function inside main
. Unlike in some other languages, we don’t need to declare the function before defining it - Kotlin allows us to use the function immediately after its definition.
When you run this program, it will output:
5040
13
The first number (5040) is the factorial of 7, and the second number (13) is the 7th Fibonacci number.
Recursion can be a powerful tool, but it’s important to use it judiciously. For large inputs, recursive solutions can lead to stack overflow errors. In such cases, iterative solutions or tail-recursive functions (which Kotlin can optimize) might be more appropriate.
Next, we’ll explore more Kotlin concepts and features.