In the following example of a Scala function:
@tailrec def someFunction( ... ): Unit = {
Is the @tailrec
annotation doing anything useful or is it just nice to know that this is a tail recursion?
In Scala 2.8, you will also be able to use the new @tailrec annotation to get information about which methods are optimised. This annotation lets you mark specific methods that you hope the compiler will optimise. You will then get a warning if they are not optimised by the compiler.
The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.
The nice thing about Scala is that tail recursive methods are automatically optimized to not allocate unnecessary stack frames.
< Scala. Recursion refers to a general method that involves defining a solution or object in terms of itself. Recursive functions refer to a kind of function where the definition of a function includes calling the function itself.
@tailrec - will produce a compilation error if a tail call optimization cannot be performed by the compiler in the annotated method.
so yes it does do something ....
check out - http://blog.richdougherty.com/2009/04/tail-calls-tailrec-and-trampolines.html
Nimrod007' answer is sufficient, But I also like to add some points.
Adding @tailrec
definitely clears a benefit of doubt in code.
You IDE might detect function as tail recursive but Scala might not, This is why it is better to add @tailrec
to the function.
You can refer the code below.
import scala.annotation.tailrec
object Application extends App {
println("Hello World")
val i = 60000
// val i = 1000
GetSum().trueTailRecursion(i)
println("\nCompleted")
GetSum().maybeTrueTailRecursion(i)
}
case class GetSum() {
def maybeTrueTailRecursion(i: Int): Int = {
print(".")
if(i==1) 1
else maybeTrueTailRecursion(i - 1)
}
@tailrec
final def trueTailRecursion(i: Int): Int = {
print(".")
if(i==1) 1
else trueTailRecursion(i - 1)
}
}
In the above example, trueTailRecursion will be able to print dotted line but maybeTrueTailRecursion will crash with StackOverFlowError. Although the function is same.
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