Do I need to use @tailrec in Scala?

@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.