This is the fifth of several posts describing the evolution of scala.concurrent.Future
in Scala 2.12.x
.
For the previous post, click here.
Deprecations: onSuccess and onFailure
Since its inception and subsequent inclusion in the Scala Standard Library, Future
has had 3 distinctly identifiable callback methods. onComplete
, onSuccess
, and onFailure
.
Now, you’re perhaps asking yourself why it is that onSuccess
and onFailure
are special-cases of onComplete
, operating on eiter side of success/failure? Well, at some point it was conceived as useful.
“But…”, I hear you say, “isn’t foreach
just a total version of onSuccess
?” Well, yes it is. So let’s use that instead, or onComplete
!
So, if you call someFuture.onSuccess(somePartialFunction)
in Scala 2.12.x you’ll get the following deprecation message:
use
foreach
oronComplete
instead (keep in mind that they take total rather than partial functions)
And then I hear you thinking “But, if onSuccess
is the partial version of foreach
, doesn’t that mean that onFailure
is the partial version of failed.foreach
?” YES—exactly that!
This is why `someFuture.onFailure(somePartialFunction)´ in Scala 2.12.x yields this deprecation message:
use
onComplete
orfailed.foreach
instead (keep in mind that they take total rather than partial functions)
Worth keeping in mind, as with all the callbacks & foreach
—there is no guaranteed order of execution of callbacks attached to the same Future
.
To illustrate:
val someFuture: Future[Missile] = …
someFuture.foreach(_.neutralize(PERMANENTLY))
someFuture.foreach(_.launch(target))
//Could be executed in any order and not unlikely in parallel
Benefits:
- Promotion of for-comprehension compatible API instead of callbacks
- In the end there’ll be fewer methods on Future, being less confusing as to what to use and when
onComplete
then remains as a performance-optimization oftransform
, not having to createFuture
s to return.
Click here for the next part in this blog series.
Cheers,
√