【问题标题】:Idomatic way to get Option value or else map into eitherT获取 Option 值或映射到 eitherT 的惯用方式
【发布时间】:2020-08-26 18:28:40
【问题描述】:

我有一个选项值传递到我的方法 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 如果它不存在惯用语,因为类型不符合我在上面编写代码的方式。

【问题讨论】:

  • Option(Bar) 是错字吗?那不是一个有效的类型。你是说Option[Bar] 吗?想要确保我们拥有您正在编译的确切代码
  • 是的,这是一个错字,我的意思是 Option[Bar]

标签: scala higher-order-functions


【解决方案1】:

也许EitherT.fromOptionorElse 的组合就像这样

def foo(barOpt: Option[Bar], barId: BarId): EitherT[Future, Error, Bar] =
  EitherT.fromOption[Future](barOpt, someError).orElse(fetchBar(barId))

【讨论】:

    【解决方案2】:

    另一种方法是使用Option.fold

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

    【讨论】:

      猜你喜欢
      • 2012-02-08
      • 2013-05-21
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 2020-07-29
      • 2012-06-28
      • 1970-01-01
      • 2013-03-08
      相关资源
      最近更新 更多