获取 Option 值或映射到任一 T 的惯用方法
Idomatic way to get Option value or else map into eitherT
我有一个选项值传递到我的方法 Foo
def Foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] = {
for {
bar <- barOpt.getOrElse(fetchBar(barId))
} yield bar
}
现在 bar 是一个 Option[Bar],而 fetchBar 是一个 EitherT[Future, Error, Bar]。我如何从选项中提取 bar 或 fetchBar 如果它不惯用地存在,因为类型不符合我上面编写代码的方式。
也许 EitherT.fromOption
和 orElse
的组合是这样的
def foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] =
EitherT.fromOption[Future](barOpt, someError).orElse(fetchBar(barId))
另一种方法是使用 Option.fold
。
def foo(barOpt: Option[Bar]): EitherT[Future, Error, Bar] =
barOpt.fold(ifEmpty = fetchBar(barId))(bar => EitherT.pure[Future, Error](bar))
我有一个选项值传递到我的方法 Foo
def Foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] = {
for {
bar <- barOpt.getOrElse(fetchBar(barId))
} yield bar
}
现在 bar 是一个 Option[Bar],而 fetchBar 是一个 EitherT[Future, Error, Bar]。我如何从选项中提取 bar 或 fetchBar 如果它不惯用地存在,因为类型不符合我上面编写代码的方式。
也许 EitherT.fromOption
和 orElse
的组合是这样的
def foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] =
EitherT.fromOption[Future](barOpt, someError).orElse(fetchBar(barId))
另一种方法是使用 Option.fold
。
def foo(barOpt: Option[Bar]): EitherT[Future, Error, Bar] =
barOpt.fold(ifEmpty = fetchBar(barId))(bar => EitherT.pure[Future, Error](bar))