1

The scala standard library seems to offer two methods for ensuring a recursive function does not cause a stack overflow.

One is the @tailrec annotation, which supposedly causes the compiler to do something differently, or try extra hard to attempt tail recursion.

The other method is to actually change your function signature to return TailRec[T], and then use the TailCalls.done and TailCalls.tailcall functions to wrap your return values.

What is the difference? Is there any reason at all to use TailRec when the compiler seems to be able to do it for me?

qwwqwwq
  • 6,999
  • 2
  • 26
  • 49
  • 1
    Echoing @MikeAllen's answer: `@tailrec` does _not_ cause the compiler to do anything differently except to terminate if the annotated method is _not_ tail recursive. If it _is_ tail recursive then there is no difference if the method is annotated or not. If it is _not_ tail recursive the compiler makes no attempt to fix it. – jwvh May 03 '17 at 05:53

1 Answers1

4

The @tailrec annotation is a tail recursion guarantee. If a function annotated with @tailrec is not actually tail recursive, then compilation will fail. (Since a tail recursive function will not result in a stack overflow, this guarantee is particularly useful in production code.)

scala.util.control.TailCalls is a mechanism for implementing tail recursion using trampolining - refer to this question for more information.

Community
  • 1
  • 1
Mike Allen
  • 8,139
  • 2
  • 24
  • 46