title: Tail Recursive Factorial Function in Scala
body: <p>I thought that the factorial function below is tail-recursive, when I tested it, works fine till 10 and becomes weird at 20 (negative output) and when I insert 100, the answer is 0:</p>
  <pre><code>def factorial(n: Int, m: Int = 1): Int = 
      if (n == 0) m else fact(n-1, m * n)
  </code></pre>
  <p>but when I put <strong>@tailrec</strong> above it, I get the following error:</p>
  <pre><code>error: not found: type tailrec
  </code></pre>
  <p>I can't understand why this function is not tail-recursive. A stack-recursive factorial function is:</p>
  <pre><code>def factorial(n: Int): Int = 
      if (n == 0) 1 else n * factorial(n-1)
  </code></pre>
  <p>The above function modifies the external expression <strong>after else</strong> at each recursive call. Whereas the first function only modifies what's inside the function. Now, to make a recursive factorial function, what they do is create a function inside a function. But, can a recursive factorial function be created just with the body of the first function in this question?</p>
  <p>Also, is the <strong>&quot;m&quot;</strong> in the former function a variable?</p>
  <p>Edit: Now after doing what is suggested in the <a href="https://stackoverflow.com/a/64292980/8237236"><strong>answer</strong></a>,
  I get the error message if a function is not tail-recursive:</p>
  <pre><code>error: could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position
  </code></pre>