我不知道如何准确描述,请参阅代码
def callForever(f: Future[Int]): Unit = {
f.onComplete {
case Failure(e) =>
//do something
case Success(c) =>
// do again
val nextConn: Future[Int] = connection()
callForever(nextConn)
}
}
它是一个正常的递归,实际上,我用它来监听套接字等待异步连接 因为它总是在运行,我想让它变得更好,我可以通过尾部方式重构它吗?
答案 0 :(得分:1)
我只是觉得你可能想看看这种做法对我来说有点好看的方式:
import scala.concurrent.Future
import scala.util.{Failure, Success, Random}
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Created by Alex on 2/29/2016.
*/
object Test {
def giveMeValue:Future[Int] = Future.successful{Random.nextInt()}
def callForever(f:Future[Int]):Future[Int] = {
println("iteration")
f flatMap(i => {println(i); callForever(giveMeValue)})
}
def main(args: Array[String]) {
callForever(giveMeValue)
while(true){}
}
}