title: How do I make a function involving futures tail recursive?
body: <p>In my Scala app, I have a function that calls a function which returns a result of type Future[T].  I need to pass the mapped result in my recursive function call.  I want this to be tail recursive, but the map (or flatMap) is breaking the ability to do that.  I get an error "Recursive call not in tail position."</p>
  
  <p>Below is a simple example of this scenario.  How can this be modified so that the call will be tail recursive (without subverting the benefits of Futures with an Await.result())?</p>
  
  <pre><code>import scala.annotation.tailrec
  import scala.concurrent.{Await, Future}
  import scala.concurrent.duration._
  
  implicit val ec = scala.concurrent.ExecutionContext.global
  
  object FactorialCalc {
    def factorial(n: Int): Future[Int] = {
  
      @tailrec
      def factorialAcc(acc: Int, n: Int): Future[Int] = {
        if (n &lt;= 1) {
          Future.successful(acc)
  
        } else {
          val fNum = getFutureNumber(n)
          fNum.flatMap(num =&gt; factorialAcc(num * acc, num - 1))
        }
      }
  
      factorialAcc(1, n)
    }
  
    protected def getFutureNumber(n: Int) : Future[Int] = Future.successful(n)
  }
  
  Await.result(FactorialCalc.factorial(4), 5.seconds)
  </code></pre>