@laiboonh here is a very simple example of using OptionT that you may want to use as a stepping stone to warm up on OptionT before looking at @tpolecat’s example, which is the definitive answer to your question:
import cats.data.OptionT
import cats.implicits._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.execute.Result
import org.specs2.mutable.Specification
import scala.concurrent.Future
class Temp(implicit ee: ExecutionEnv) extends Specification {
"OptionT" should {
"allow me to treat Future[Option[Int]] as a monad" in test
}
def test: Result = {
val futureMaybeX : Future[Option[Int]] = Future.successful(Some(3))
val futureMaybeY : Future[Option[Int]] = Future.successful(Some(5))
val futureMaybeZ : OptionT[Future, Int] =
for {
x <- OptionT(futureMaybeX)
y <- OptionT(futureMaybeY)
} yield x + y
futureMaybeZ.value must beSome(8).await
}
}