8

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?

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
JamboShrimp
  • 83
  • 1
  • 4

2 Answers2

10

@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

Mark Lister
  • 1,103
  • 6
  • 16
Nimrod007
  • 9,825
  • 8
  • 48
  • 71
  • 6
    "While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes." – zero323 Nov 04 '13 at 09:58
  • 2
    i think my answer is with enough data to answer the question, if you want to read more read more ... – Nimrod007 Nov 04 '13 at 10:16
3

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.

shri
  • 63
  • 8