2016-04-30 13 views
3

私はScalaには新しく、すべての結果を得るまで、十分に異なるオフセットのAPI呼び出しを行うことです。すべての結果を取得するためのスカラ再帰的なAPI呼び出し

ここに私が持っているものの簡略化されたバージョンがあり、それを行うためのもっと慣用的なScalaの方法があるのだろうかと思っていました。 (コードサンプルは100%正確ではないかもしれない、それはちょうど私が例として立て何か)otherProductsパラメータを渡す

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 
} 

はちょうどいい感じていない:任意の提案を事前にP

感謝を:)

答えて

4

これは、テール再帰実装を公開しているようです。これは、関数型プログラミングの実装の詳細と少し似ています。 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アキュムレータの名前。

関連する問題