i'm new to scala and i'm currently practicing in the worksheet. I noticed that @tailrec doesn't work in the worksheet even though i added the import
import scala.annotation.tailrec
This is the version of scala i'm using
Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL
Is there a way to get it to work? Thanks
The issue you described is a bug in the Eclipse IDE for Scala: https://scala-ide-portfolio.assembla.com/spaces/scala-ide/tickets/1001636#/activity/ticket
The workaround is to put the @tailrec in a def or a different object.
e.g.:
package tailrecfunc
import scala.annotation.tailrec
object Session17 {
val block = {
@tailrec
def tailrecfunc(n: Int): Int =
if(n == 0) n; else tailrecfunc(n - 1)
tailrecfunc(4)
}
}
This way the scala interpreter will warn you when the function is not tail recursive
Be careful that you are not mistaking how the @tailrec
annotation works - it does not force a function to be optimised by the compiler in a "tail-recursive manner" (the compiler will alwasys make that optimisation anyway, if it can).
Rather it is simply a marker that you can use to tell the compiler "I think this function has been successfully written in a tail-recursive manner, please tell me if you cannot optimise it that way."
That is, use it where you want to be sure that you have correctly written a function intended to be tail-recusive, and the compiler can point out when you get it wrong.
Does that make sense of what you are seeing? I can't say anything more useful without seeing example code where you have used the annotation.
First define and stub the function you want to annotate, then go back and add the annotation.
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