Last active
February 9, 2016 20:46
-
-
Save lucianenache/d9012a8baa7fe38cb694 to your computer and use it in GitHub Desktop.
Scala constructs document for resolving futures, options, and other monadic types
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
//////////////////////////////////////////// Option //////////////////////////////////////////////////////////////////////// | |
obj.fold(defaultVal)(func) | |
obj.map(func).getOrElse(defaultVal) | |
obj match { | |
case Some(x) => func(x); | |
case None => defaultVal | |
} | |
// composed Option[A] | |
val oa: Option[String] = Some("a") | |
val ob: Option[String] = Some("b") | |
val oab : Option[String] = for{ | |
a <- oa | |
b <- ob | |
} yield a+b | |
//////////////////////////////////// Future //////////////////////////////////////////////////////////////////////// | |
val result = Await.result(futureResponse.map(response => response.parseJson.convertTo[SomeEntity]),30.seconds) | |
// Non blocking composed futures | |
def fa: Future[String] = Future("a") | |
def fb(a: String): Future[String] = Future(a+"b") | |
val fab : Future[String] = for{ | |
a <- fa | |
ab <- fb(a) | |
} yield ab | |
// COMPOSED Future[Option[T]] | |
// (*) : In the for, call fob with the value inside the option and get a Future[Option[String]]. | |
// Doing this, you can compose result from foa and fob and keep consistent types. | |
val composedAB: Future[Option[String]] = foa.flatMap { | |
case Some(a) => fob(a) //(*) | |
case None => Future.successful(None) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment