Created
November 29, 2017 04:53
-
-
Save prassee/47f92c254ffe41ea41c7adfae26f45b4 to your computer and use it in GitHub Desktop.
Converting Future[Option[T]] to Future[T] using transform function
This file contains hidden or 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
// this is provided by | |
// "io.github.scala-hamsters" %% "hamsters" % "2.1.2" | |
// put the above as dependency in build.sbt | |
import io.github.hamsters.FutureOption | |
import scala.concurrent.Future | |
object FutOfOptionsTest { | |
import io.github.hamsters.FutureOption | |
def main(args: Array[String]): Unit = { | |
val result: FutureOption[Int] = | |
for { | |
/** | |
* the FutureOption is a monad transformer. It helps to get rid | |
* of nested maps on the nested types of Future. | |
*/ | |
f1 <- FutureOption(Future(Option(1))) | |
f2 <- FutureOption(Future(Option(2))) | |
f3 <- FutureOption(Future(Option(3))) | |
result = f1 + f2 + f3 | |
} yield result | |
val x: Future[Int] = HamstersFutureOptionUnwrapper(result, { | |
case Some(a) => a | |
case None => -1 | |
}, AsyncException("")).asFutureofT | |
} | |
} | |
case class AsyncException(a: String) extends Exception | |
case class HamstersFutureOptionUnwrapper[T](fopt: FutureOption[T], transformFn: Option[T] => T, exception: Exception) { | |
def asFutureofT: Future[T] = fopt.future.transform(transformFn, f => exception) | |
} | |
case class FutureOptionUnwrapper[T](fut: Future[Option[T]], transformFn: Option[T] => T, exception: Exception) { | |
def asFutureofT: Future[T] = fut.transform(transformFn, f => exception) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment