user3635344
user3635344

Reputation: 13

Scala: Recursion with future Stack overflow error

Consider below code snippet. Too many take() calls will result in stack overflow error. What is the good strategy to overcome such scenarios?

def take(): Future[Int] = {
    val processResponseF: Future[Boolean] = performSomeAction()
    processResponseF.flatMap(
      processResponse => {
        if(processResponse)
          Future.successful(100)
        else
          take()
      }
    )
  }

def performSomeAction(): Future[Boolean] = {
  //This returns future of boolean
}

Assumption - 1. Method signature should not be changed

Upvotes: 0

Views: 326

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Too many take() calls will result in stack overflow error.

It won't. When a method that returns a Future recursively calls itself, all that method knows is that it has a future value that will be filled (maybe) later. The actual code is executed on a different stack, as it needs to be done asynchronously from the original call, and may not even happen on the same thread.

Upvotes: 3

Related Questions