Kotlin replication

fun fact(x: Int): Int{
    tailrec fun factTail(y: Int, z: Int): Int{
        if (y == 0) return z
        else return factTail(y - 1, y * z)
    }
    return factTail(x, 1)
}

Can someone explain to me how this recursion function works in kotlin?

+4
source share
2 answers

I will begin to say that the keyword is tailrecused only as an optimization for the compiler, which will try to express the function using a loop, and not with recursion, avoiding the risk of a stack overflow .

If we avoid recursion, the function might look something like this:

 fun fact(x: Int): Int {
    var result = x
    for (i in x - 1 downTo 1) {
        result *= i
    }
    return result
 }
+2
source

There is a big risk when you use recursion in Java, which is stackoverflow. stack

, Java. . , StackOverflow.

. , Tail Call. , . . , StackOverflow. .

Kotlin tailrec, . , , try/catch/finally.

+2

Source: https://habr.com/ru/post/1688429/


All Articles