E097: Tailrec Not Applicable

This error is emitted when the @tailrec annotation is used on a method that cannot be optimized for tail recursion.

Tail recursion optimization requires that:

  • The annotated symbol is a method
  • The method is not abstract
  • The method is either private or final (so it can't be overridden)
  • The method contains recursive calls in tail position

Example

import scala.annotation.tailrec

class Example:
  @tailrec def factorial(n: Int, acc: Int = 1): Int =
    if n <= 1 then acc
    else factorial(n - 1, n * acc)

Error

-- [E097] Syntax Error: example.scala:4:15 -------------------------------------
4 |  @tailrec def factorial(n: Int, acc: Int = 1): Int =
  |               ^
  |TailRec optimisation not applicable, method factorial is neither private nor final so can be overridden

Solution

// Make the method final or private
import scala.annotation.tailrec

class Example:
  @tailrec final def factorial(n: Int, acc: Int = 1): Int =
    if n <= 1 then acc
    else factorial(n - 1, n * acc)
// Or use private
import scala.annotation.tailrec

class Example:
  @tailrec private def factorial(n: Int, acc: Int = 1): Int =
    if n <= 1 then acc
    else factorial(n - 1, n * acc)