Scala递归API调用可获取所有结果

Sor*_*aei 4 recursion functional-programming scala

我对Scala还是很陌生,我想实现的目标是对具有不同偏移量的API进行足够的调用,直到获得所有结果为止。

这是我所拥有的简化版本,我想知道是否还有一种更惯用的Scala方法。(代码示例可能不是100%准确,这只是我作为示例提出的内容)

def getProducts(
                 limit: Int = 50,
                 offset: Int = 0,
                 otherProducts: Seq[Product] = Seq()): Future[Seq[Product]] = {

  val eventualResponse: Future[ApiResponse] = apiService.getProducts(limit, offset)

  val results: Future[Seq[Product]] = eventualResponse.flatMap { response =>

    if (response.isComplete) {
      logger.info("Got every product!")
      Future.successful(response.products ++ otherProducts)
    } else {
      logger.info("Need to fetch more data...")

      val newOffset = offset + limit
      getProducts(limit, newOffset, otherProducts ++ response.products)
    }
  }

  results
}
Run Code Online (Sandbox Code Playgroud)

传递otherProducts参数只是感觉不正确:P

在此先感谢您的任何建议 :)

dmi*_*try 5

看来您已经公开了尾递归实现,这有点像函数编程中的实现细节。

对于我来说,我通常将此类函数包装到没有累加器参数(otherProducts)的外部调用中:

def getProducts(limit: Int = 50, offset: Int = 0): Future[Seq[Product]] = {
   def loop(limit: Int = 50,
             offset: Int = 0,
             acc: Seq[Product] = Seq()): Future[Seq[Product]] = ... your code with tail recursion...

   loop(limit, offset)
}
Run Code Online (Sandbox Code Playgroud)

但这只是口味的问题,如果otherProducts只是tailrec蓄能器的花哨名称,那当然是有效的。