Last active
December 28, 2015 21:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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