joesan
joesan

Reputation: 15385

Understanding Scala Futures and Promises

I'm trying to get my head around this concept. I clearly understand what Futures are. I'm little bit bemused with Promises. The code snippet below:

val p = Promise[Int]() // gives me a DefaultPromise
val f = p.future // gives me the future computation for the Promise p

Now what is the difference between the following two code snippets?

p success { 10 }

and

val x = Future {
  p success { 10 }
}

My understanding of the first one is that the p success will complete the future computation associated with that p. Is that computation asynchronous? How is that different to the second code snippet that uses a Future block to complete the Future f associated with Promise p?

Upvotes: 3

Views: 998

Answers (1)

Carlos Vilchez
Carlos Vilchez

Reputation: 2804

In your example you can consider equivalent p success { 10 } and Future(10). You will only need to extract the future from p to get the same result.

You may consider Promises as a writeable Future where you will define the success or failure of the computation. As it looks a bit imperative programming, you will probably use them in very particular cases. You can see some of those cases in this link.

Upvotes: 4

Related Questions