I'm running into quite a few places where I have something akin to
def f(s: String): Option[Long] = ...
def g(l: Long): IO[Option[Wibble]] = ...
val a: IO[Option[Wibble]] = f(param).flatMap(g).sequence.map(_.join)
Seeing the .sequence.map(_.join)
repeated over and over is starting to bother me. Is there a more idiomatic way of accomplishing the same thing?
This sounds like the use case for monad transformers, see here for an explanation in Haskell and here for a discussion in Scala.
The idiomatic method for dealing with Option
chains is to use for-comprehensions and a getOrElse
call.
val a = for {
val temp <- f(param)
val result <- Some(g(temp))
} yield result getOrElse <Default Here>
There's no getting around either having a default or raising an exception if you are going to categorically unpack the Option
since f
can return None
and g
can't accept that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With