Reputation: 35
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.
Upvotes: 1
Views: 188
Reputation: 22840
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))
Upvotes: 3
Reputation: 48410
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))
Upvotes: 4