February 2018
Intermediate to advanced
350 pages
7h 35m
English
Recursive functions are functions that invoke themselves, with some sort of condition to stop the execution. In Kotlin, a recursive function maintains a stack but can be optimized with a tailrec modifier.
Let's look at an example, an implementation of a factorial function.
First, let's take a look at a typical imperative implementation, loops, and state change in the following code snippet:
fun factorial(n: Long): Long { var result = 1L for (i in 1..n) { result *= i } return result}
It's nothing fancy nor particularly elegant. Now, let's take a look at a recursive implementation, no loops, and no state change:
fun functionalFactorial(n: Long): Long { fun go(n: Long, acc: Long): Long { return if (n <= 0) { acc } else
Read now
Unlock full access