如何通过Future.foreach回调scala中的尾递归?

时间:2015-06-24 05:09:29

标签: scala recursion callback future

考虑一个scala代码:

def myRecursiveFunction(id:string):Unit= {
    myAsyncDao.search(id).foreach {response=>
        myRecursiveFunction(response.id)
    }
}
//myAsyncDao.search returns a Future
//response have id field for further computations

如果我将@tailrec置于顶级操作函数上,请编译抱怨Recusive call not in tail position

它可以优化为尾递归吗?

1 个答案:

答案 0 :(得分:0)

怎么样

def myRecursiveFunction(id:string):Future[Unit]= {
    myAsyncDao.search(id) flatMap {response=>
        myRecursiveFunction(response.id)
    }
}

更新

def search(id: Future[Int]) = Future { 5 }

@tailrec
def myRecursiveFunction(id: Future[Int]):Future[Unit]= {
    val response = search(id)
    myRecursiveFunction(response)    
}