I think there is @tailrec
annotation to ensure the compiler will optimize a tail recursive function. Do you just put it in front of the declaration? Does it also work if Scala is used in scripting mode (for instance using :load <file>
under REPL)?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
- Testing request with CSRF Token in Play framework
- Run project with java options via sbt
The annotation is
scala.annotation.tailrec
. It triggers a compiler error if the method can't be tail call optimized, which happens if:It is placed just before the
def
in a method definition. It works in the REPL.Here we import the annotation, and try to mark a method as
@tailrec
.Oops! The last invocation is
1.+()
, notlength()
! Let's reformulate the method:Note that
length0
is automatically private because it is defined in the scope of another method.From the "Tail calls, @tailrec and trampolines" blog post:
Example:
And it works from the REPL (example from the Scala REPL tips and tricks):
The Scala compiler will automatically optimize any truly tail-recursive method. If you annotate a method that you believe is tail-recursive with the
@tailrec
annotation, then the compiler will warn you if the method is actually not tail-recursive. This makes the@tailrec
annotation a good idea, both to ensure that a method is currently optimizable and that it remains optimizable as it is modified.Note that Scala does not consider a method to be tail-recursive if it can be overridden. Thus the method must either be private, final, on an object (as opposed to a class or trait), or inside another method to be optimized.