tailrec
optimizes functions where there is tail recursion. Why doesn't the compiler just optimize it anyway?
C compilers optimize for tail recursion. You don't have to mark the method as having tail recursion. The compiler just notices that the last operation is recursive. And that's that.
Why does this seemingly excessive keyword exist? Have I missed something? Is it purely for the convenience of the compiler, and not the user?
The keyword tells the compiler that the implementation of the function is required to be tail-recursive, and causes the compiler to report an error if the function is not actually tail-recursive. It protects the user from situations when a change to the implementation of the function causes it to no longer be tail-recursive, and causes an unexpected drop in performance (or a complete failure in production due to a stack overflow error).
I'll go ahead and guess that this is to be able to more deliberately write tail-recursive functions. By requiring the keyword explicitly, you'll know that the compiler optimization will definitely happen (you won't be left guessing if the compiler optimized your function successfully or if you'll get a stack overflow at runtime), plus your code won't even compile if you break the rules of tail recursion for the function you've maked with tailrec
, as the doc states:
To be eligible for the tailrec modifier, a function must call itself as the last operation it performs.
Recall official Kotlin documentation just says that :
When a function is marked with the tailrec modifier and meets the required form, the compiler optimises out the recursion, leaving behind a fast and efficient loop based version instead
Which strongly suggests that this conversion to a loop is not warranted to take place if the tailrec keyword is not present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With