Issue
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)) }
}
Solution
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)
.
Answered By - ralphmerridew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.