Recursion in Kotlin
Kotlin supports recursive functions. Here’s a classic example.
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:
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.