How do I make a function involving futures tail recursive?

前端 未结 4 537
野性不改
野性不改 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:40

    Here's a foldLeft solution that calls another function that returns a future.

    def factorial(n: Int): Future[Int] =
      (1 to n).foldLeft(Future.successful(1)) {
        (f, n) => f.flatMap(a => getFutureNumber(n).map(b => a * b))
      }
    
    def getFutureNumber(n: Int) : Future[Int] = Future.successful(n)
    

提交回复
热议问题