简体   繁体   中英

Kotlin recursion

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)
}

Could someone please explain to me how does the above recursion function work in kotlin?

I'll start saying that the tailrec keyword is used only as an optimization for the compiler that will try to express the function with a loop and not with recursion avoiding the risk of stack overflow .

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

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

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

As above link recursion works in Java. There will be some maximum size for stack, If our recursion function is going to infinite, then it will cross the max size and it leads to StackOverflow exception. So avoid using recursion and use loop instead

Coming to the current problem. It's a special recursion which is Tail call . On that a function must call itself as the last operation it performs. Tail calls can be implemented without adding a new stack frame to the call stack. So there will not be any risk of StackOverflow. And it's supported in kotlin.

In Kotlin it uses tailrec modifier to show this special recursion. You cannot use tail recursion when there is more code after the recursive call, and you cannot use it within try/catch/finally blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM