How do I make a function involving futures tail recursive?

前端 未结 4 554
野性不改
野性不改 2020-11-29 09:52

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 t

4条回答
  •  暖寄归人
    2020-11-29 10:35

    Make factorialAcc return an Int and only wrap it in a future in the factorial function.

    def factorial(n: Int): Future[Int] = {
    
        @tailrec
        def factorialAcc(acc: Int, n: Int): Int = {
          if (n <= 1) {
            acc
          } else {
            factorialAcc(n*acc,n-1)
          }
        }
    
        future {
          factorialAcc(1, n)
        }
    }
    

    should probably work.

提交回复
热议问题