This is a port of Hamsters monad transformers to Scala 2.13.
Example : combine Future and Option types then make it work in a for comprehension. More information on why it's useful here.
import io.github.hamsters.FutureOption
import io.github.hamsters.MonadTransformers._
//import your execution context here too, for example import scala.concurrent.ExecutionContext.Implicits.global
def foa: Future[Option[String]] = Future(Some("a"))
def fob(a: String): Future[Option[String]] = Future(Some(a+"b"))
val composedAB: Future[Option[String]] = for {
a <- FutureOption(foa)
ab <- FutureOption(fob(a))
} yield ab
import io.github.hamsters.FutureTry
import io.github.hamsters.MonadTransformers._
//import your execution context here too, for example import scala.concurrent.ExecutionContext.Implicits.global
def foa: Future[Try[String]] = Future(Try("a"))
def fob(a: String): Future[Try[String]] = Future(Try(a+"b"))
val composedAB: Future[Try[String]] = for {
a <- FutureTry(foa)
ab <- FutureTry(fob(a))
} yield ab
import io.github.hamsters.FutureEither
import io.github.hamsters.MonadTransformers._
//import your execution context here too, for example import scala.concurrent.ExecutionContext.Implicits.global
def fea: Future[Either[String, Int]] = Future(Right(1))
def feb(a: Int): Future[Either[String, Int]] = Future(Right(a+2))
val composedAB: Future[Either[String, Int]] = for {
a <- FutureEither(fea)
ab <- FutureEither(feb(a))
} yield ab
If you use other combinations of F[Option[A]] or F[Either[L,R]], you can bring your own Monad
implicit instance and work with OptionT
or EitherT
. Future
and Option
instances are provided by default.
Add this to you build.sbt :
resolvers += Resolver.bintrayRepo("loicdescotte", "Hamsters")
libraryDependencies += "io.github.scala-hamsters" %% "monad-transformers" % "1.0.0"