Developus
Developus

Reputation: 1462

Scala - How to return simple raw type value from flat map?

I have a simple code, where I want to get only one boolean value, but it is contained in a Future object:

def getValue(arg: String) : Boolean = for {
    data <- SomeObject.getData(arg) //SomeObject is in class constructor 
    value = data.getBooleanValue
} yield value

The problem here is I need to return Future[Boolean] instead of simple boolean. How I could change it to return only raw type?

Upvotes: 0

Views: 151

Answers (1)

Tim
Tim

Reputation: 27356

As soon as you call an API that returns Future you need to chain your code to execute when that Future completes as far as you possibly can. Avoid waiting for Future to complete as long as possible.

So change the method to return Future:

def getValue(arg: String): Future[Boolean] =
  SomeObject.getData(arg).map(_.getBooleanValue)

Then rather than calling

nextMethod(getValue(myArg))

Use map on the Future like this:

getValue(myArg).map{ bool =>
  nextMethod(bool) // next processing step
}

This will give a new Future that will contain the result of the next step of the processing.

While this does require re-working the calling code, Scala makes this kind of code very easy to write. Keep chaining operations onto the previous Future until the processing is complete.

In most cases the code will end up with a side-effect operation such as sending a message or writing a file, and in this case there is no need to wait for the Future to complete.

On the rare occasions when you do need to wait for a Future, use Await.result to recover the final result of the chain of Futures

Upvotes: 3

Related Questions