【发布时间】: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