Back to Scala3

E097: Tailrec Not Applicable

docs/_docs/reference/error-codes/E097.md

3.8.41.6 KB
Original Source

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

scala
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

scala
-- [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

scala
// 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)
scala
// 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)
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>