Q:

Idomatic way to get Option value or else map into eitherT

I have an option value passed into my method Foo
def Foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] = {

    for {
        bar <- barOpt.getOrElse(fetchBar(barId))
    } yield bar
}

Now bar is an Option[Bar], while fetchBar is an EitherT[Future, Error, Bar]. How can I either extract bar from the option or fetchBar if it doesn't exist idiomatically, as the types do not work out the way I have written the code above.

A:

Perhaps combination of EitherT.fromOption and orElse like so
def foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] =
  EitherT.fromOption[Future](barOpt, someError).orElse(fetchBar(barId))

A:

Another approach would be using Option.fold.
def foo(barOpt: Option[Bar]): EitherT[Future, Error, Bar] =
  barOpt.fold(ifEmpty = fetchBar(barId))(bar => EitherT.pure[Future, Error](bar))

