Recursive OR loop

Have you ever been frustrated when writing a method that involves recursive calls? It’s easier to understand the meaning and flow of the method with recursion, but you have to abandon recursion and silently change your code to loop in order to avoid StackOverFlow with too many recursive calls? So, is it possible for me to keep my code recursive but execute it in a circular fashion? That seems naive, but Kotlin users might have the luck to do so.

tailrec

JsonToKotlin (json > Kotli Data Class) found a number of recursive calls in one of its classes, as follows:

Then all of a sudden the words “tail-recursion” come to mind, and tail-recursion is a recursive function that is said to be tail-recursion if all of the recursive calls in a function occur at the end of the function. Tail-recursion optimization is to eliminate the recursion by automatically converting to loop at compile time, so as to preserve the recursive readability of the code and solve the problem of stack space. Since I knew that JAVA does not support tail-recursive optimization, I started looking for Kotlin to see if he had tail-recursive optimization.

The keyword for tail-recursive optimization is easily found in the official documentation: tailrec

tailrec marks a function as tail-recursive (allowing the compiler to replace recursion with iteration)

validation

So I started the experiment. I wrote the code conforming to the form of tail recursion first, and checked whether the optimization of tail recursion was achieved by comparing the bytecode DEcompile of Kotlin code.

By comparison, it’s not hard to see that TailREc does exactly what JAVA cannot.