简体   繁体   中英

In Scala futures, should I make my functions return a Future or return a Try?

When I use Scala futures I feel confused as to whether I should return a future or return a Try. Since my code could fail, so I expect to return a Try which may have success or failure and the user of the function could use the function to create a future.

Future s can fail, yes, but that failure is self-contained--it's not going to propagate to the rest of your code. Future is very similar to Try in that sense, and in fact the value it holds is Option[Try[T]] .

So when you map a Future , you'll only be handling the Success case of it's value , and if you want to handle the failures, you can use recover or recoverTo .

Future callback functions also deal with the Try directly:

 Future(...).onComplete {
     case Success(value) => ...
     case Failure(throwable) =>
 }

Stick with Future when you need async results, as it uses Try internally anyway.

If you want to get your result asynchronously you should use Future . Future has 2 types of results: Success and Failure which as you know are descendants of Try, so in any case you'll catch the failre if it happens.

Let's say I was designing yet another actor API. What should I use for result type of send? If I want clients of my code to return back to it's business as far as it possible (in other words, fire-and-forget type of sending) and process response somewhere in the future I would go with the Future . If I want to block until response will come back I will pick Try .

Hope, that makes things a bit clear for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM