8

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?

rwallace
  • 127
  • 4

2 Answers2

1

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.

1

This sounds like the use case for monad transformers, see here for an explanation in Haskell and here for a discussion in Scala.

Ozymandias
  • 521
  • 2
  • 16