【问题标题】:Scala recursive API calls to get all the resultsScala 递归 API 调用以获取所有结果
【发布时间】:2016-08-25 11:31:53
【问题描述】:

我对 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
}

传递otherProducts 参数感觉不对:P

提前感谢您的任何建议:)

【问题讨论】:

    标签: scala recursion functional-programming


    【解决方案1】:

    看来你已经暴露了尾递归实现,这有点像函数式编程中的实现细节。

    就我而言,我通常将此类函数包装到没有累加器参数的外部调用中 (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)
    }
    

    但这只是个人喜好问题,当然如果otherProducts 只是tailrec 累加器的一个花哨的名字也是有效的。

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多