Skip to content

Instantly share code, notes, and snippets.

@olim7t
Last active December 28, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olim7t/7562960 to your computer and use it in GitHub Desktop.
Save olim7t/7562960 to your computer and use it in GitHub Desktop.
Coursera / Reactive Programming in Scala / Week 3 / Combinators on Futures Sample code for answers C and D of the quiz.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Try, Success, Failure}
val f: Future[Int] = Future(1 / 0)
// answer C
def applyC[T](f: Future[T]): Future[Try[T]] = f.map(x => Try(x))
// answer D
def applyD[T](f: Future[T]): Future[Try[T]] = f.map(s => Success(s)) recover { case t => Failure(t) }
applyC(f) onComplete { t => println(s"onComplete input: $t") }
// onComplete input: Failure(java.lang.ArithmeticException: / by zero)
applyD(f) onComplete { t => println(s"onComplete input: $t") }
// onComplete input: Success(Failure(java.lang.ArithmeticException: / by zero))
// Reminder: Future[X].onComplete has the signature: onComplete[U](func: (Try[X]) ⇒ U)
// In our case, X = Try[Int], so:
// applyC's input is a Failure[X], meaning: the future failed
// applyD's input is a Success[X], meaning: the future has succeeded, and the result is a Failure[Int]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment