考虑一个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
。
它可以优化为尾递归吗?
答案 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)
}