Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods ready and result of Future in Scala cannot be called directly

I noticed that methods ready and result of scala.concurrent.Future cannot be invoked directly. When I call them in REPL I get an error. Thus I have to call Await.ready and Await.result instead.

It is Ok but looks a bit awkward. So now I wonder:

  • why they cannot be invoked directly;
  • why they are exposed as public API in that case.
like image 739
Michael Avatar asked May 17 '13 16:05

Michael


People also ask

Which method is used to execute the future in Scala?

The onComplete method is general in the sense that it allows the client to handle the result of both failed and successful future computations. In the case where only successful results need to be handled, the foreach callback can be used: Scala 2. Scala 3.

How does Scala Future work?

Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.

What is Future and promise in Scala?

The Promise is a writable, single-assignment container that completes a Future. The Promise is similar to the Future. However, the Future is about the read-side of an asynchronous operation, while the Promise is about the write-side.

What is await result in Scala?

Await. result tries to return the Future result as soon as possible and throws an exception if the Future fails with an exception while Await. ready returns the completed Future from which the result (Success or Failure) can safely be extracted.


1 Answers

The reasons are laid out in official doc:

The Future trait implements the Awaitable trait with methods method ready() and result(). These methods cannot be called directly by the clients– they can only be called by the execution context.

That way library designers enforce you to use those methods in proper environment (execution context, perhaps third party, or via Awaitable object to denote blocking operations explicitly).

like image 144
om-nom-nom Avatar answered Oct 18 '22 21:10

om-nom-nom