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?
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 .
tailrec
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 }
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.
Source: https://habr.com/ru/post/1688429/More articles:Get the last div with the same data attribute - javascriptPython scope between local and global - pythonArray Univ var ([x, y] = .. T) - prolog - prolog"Sorry. Something went wrong and we need to start all over again." with Microsoft Bot Service with LUIS template - luisSpring Cloud configuration server using an SSH key for Git and runs in Docker - gitIn Powershell, how can I replace a string containing a question mark? - replaceIs there a simple DWARF CFI clause for functions that set a regular frame pointer? - debuggingreceiving error: unable to read state status undefined - undefinedhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1688433/tensorflow-serving-no-assets-to-savewrites-when-exporting-models&usg=ALkJrhi_gwJ7BpjLDpoGdgutPu1zkJHW4wUse componentWillMount or componentDidMount lifecycle functions to request async in React - javascriptAll Articles