This function returns a list containing all numbers from n to 0.
If I deleted the "if" statement the function doesn't work, even if the parameters aren't 0.
Why is that?
fun countDown (n : Int): List<Int> {
if (n == 0) {
return listOf(0)
}
return mutableListOf(n).also { it.addAll(countDown(n - 1)) }
}
Your code calls it.addAll(countDown(n-1)), specifically calling countDown(n-1)
So a direct call to, say, countDown(3) will call countDown(2); countDown(2) calls countDown(1); countDown(1) calls countDown(0).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments