xyz_scala
xyz_scala

Reputation: 471

recursive call Future in scala

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)
            }
        }
    }
}

I m trying call getexecution method in future recursively but not able to get inside future. May return type is Unit not able to get inside future. How to execute future call recursively?

Upvotes: 1

Views: 2310

Answers (1)

Viktor Klang
Viktor Klang

Reputation: 26579

Here's an example of a recursive implementation which is the closest to your original code.

//Using Scala 2.12 (for 2.11 replace Future.unit with Future.successful(())

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)
    }
}

Executing it looks like this:

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

Upvotes: 3

Related Questions