scala中的递归调用 objectfuture1{ def main(参数:数组[字符串]):单位={ def getexecute(i:Int){ println(“开始线程”+i) 线程睡眠(1000L) println(“螺纹末端”+i) } 变量n=10 println(“heelo”+n) def execute_future(n:Int):单位=未来{ println(“你好”) if(n

scala中的递归调用 objectfuture1{ def main(参数:数组[字符串]):单位={ def getexecute(i:Int){ println(“开始线程”+i) 线程睡眠(1000L) println(“螺纹末端”+i) } 变量n=10 println(“heelo”+n) def execute_future(n:Int):单位=未来{ println(“你好”) if(n,scala,recursion,scala-collections,Scala,Recursion,Scala Collections,这里是一个递归实现的示例,它最接近您的原始代码 //使用Scala 2.12(对于2.11,将Future.unit替换为Future.successful(()) Future.unit.flatMap{…}和Future{…}之间有什么区别?也许这不是正确的问题…但是为什么Future.unit.flatMap是必要的?Future{}是Future.unit.map。我们需要的是flatMap来“递归”。有关样式的详细信息,请阅读此文档: object future1 { def

这里是一个递归实现的示例,它最接近您的原始代码

//使用Scala 2.12(对于2.11,将Future.unit替换为Future.successful(())


Future.unit.flatMap{…}
Future{…}
之间有什么区别?也许这不是正确的问题…但是为什么
Future.unit.flatMap
是必要的?
Future{}
Future.unit.map
。我们需要的是
flatMap
来“递归”。有关样式的详细信息,请阅读此文档:
object future1 {
    def main(args: Array[String]): Unit = {
        def getexecute(i:Int){
            println("start thread "+i)
            Thread.sleep(1000L)
            println("end of thread "+i)
        }       
        var n=10
        println("heelo"+n)
        def execute_future(n:Int):Unit = Future{
            println("hello")
            if(n<1){
                println("heelo")
                1
            }           
            else{
                println("get into future")
                getexecute(n)
                execute_future(n-1)
            }
        }
    }
}
object future1 {
    import scala.concurrent._
    import scala.concurrent.duration._
    import ExecutionContext.Implicits._
    def main(args: Array[String]): Unit = {
        def getexecute(i:Int){
            println("start thread "+i)
            Thread.sleep(1000L)
            println("end of thread "+i)
        }       
        def execute_future(n:Int):Future[Int] = Future.unit flatMap { _ =>
            println("hello")
            if(n<1) {
                println("heelo")
                Future.successful(1)
            } else {
                println("get into future")
                getexecute(n)
                execute_future(n-1)
            }
        }

        Await.result(execute_future(10), 15.seconds)
    }
}
scala> future1.main(Array())
hello
get into future
start thread 10
end of thread 10
hello
get into future
start thread 9
end of thread 9
hello
get into future
start thread 8
end of thread 8
hello
get into future
start thread 7
end of thread 7
hello
get into future
start thread 6
end of thread 6
hello
get into future
start thread 5
end of thread 5
hello
get into future
start thread 4
end of thread 4
hello
get into future
start thread 3
end of thread 3
hello
get into future
start thread 2
end of thread 2
hello
get into future
start thread 1
end of thread 1
hello
heelo