Skip to content

Commit

Permalink
Merge pull request #6 from viktorklang/futures-in-scala-2.12-part4
Browse files Browse the repository at this point in the history
Futures in Scala 2.12: Part 4 — transformWith
  • Loading branch information
viktorklang committed Feb 23, 2016
2 parents 09f63eb + a50f3ba commit e972b13
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion Futures-in-Scala-2.12-part-4.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,34 @@ Remember to use the solution with the least power which will suffice for the tas

And, before you say anything, yes, `flatMap` and `recoverWith` are implemented in terms of `transformWith` in Scala 2.12!

EDIT:

Here's `flatMap`:

~~~scala
def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S] = transformWith {
case Success(s) => f(s)
case Failure(_) => this.asInstanceOf[Future[S]] //Safe cast to reuse current, failed, Future
}
~~~

And here's `recoverWith`:

~~~scala
def recoverWith[U >: T](pf: PartialFunction[Throwable, Future[U]])(implicit executor: ExecutionContext): Future[U] =
transformWith {
case Failure(t) => pf.applyOrElse(t, (_: Throwable) => this) //Pass along current failure if no match
case Success(_) => this
}
~~~

###Benefits:

1. Ultimate power, for when you require it

[Here's the RSS feed of this blog](https://github.com/viktorklang/blog/commits/master.atom) and—as I love feedback—please [share your thoughts](https://github.com/viktorklang/blog/issues/3).

To comment on the blog post itself, [click here](https://github.com/viktorklang/blog/pull/4) and comment on the PR.
To comment on the blog post itself, [click here](https://github.com/viktorklang/blog/pull/4/files) or [here](https://github.com/viktorklang/blog/pull/6/files) and comment on the PR.

Stay tuned for many more updates about Futures in Scala 2.12!

Expand Down

0 comments on commit e972b13

Please sign in to comment.