Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@tailrec error in scala eclipse worksheet: expected start of definition

Tags:

scala

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

like image 995
SamAko Avatar asked Sep 21 '13 17:09

SamAko


3 Answers

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

like image 166
aPokeIntheEye Avatar answered Nov 09 '22 17:11

aPokeIntheEye


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.

like image 4
Shadowlands Avatar answered Nov 09 '22 17:11

Shadowlands


First define and stub the function you want to annotate, then go back and add the annotation.

like image 1
joescii Avatar answered Nov 09 '22 19:11

joescii