【问题标题】:Scala - How to Combine EitherT with Either in For ComprehensionScala - 如何将 EitherT 与 Either 结合起来以供理解
【发布时间】:2018-08-30 07:19:38
【问题描述】:

假设我有以下设置:

def foo: Either[Error, A] = ???
def bar: EitherT[Future, Error, B] = ???
case class Baz(a: A, b: B)

如何使用 for comprehension 来实例化 Baz 类?我试过了:

val res = for {
  a <- foo
  b <- bar
} yield Baz(a, b)

但是,结果的类型为Either[Error, Nothing]。我不知道在这种情况下正确的返回类型是什么,但显然我不想要Nothing...

结合EitherEitherT进行理解的正确方法是什么?

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    使用EitherT.fromEither函数从Either创建EitherT

    import cats.data._
    import cats.implicits._
    
    def foo[A]: Either[Error, A] = ???
    def bar[B]: EitherT[Future, Error, B] = ???
    case class Baz[A, B](a: A, b: B)
    
    def res[A, B] = for {
      a <- EitherT.fromEither[Future](foo[A])
      b <- bar[B]
    } yield Baz(a, b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 2019-03-16
      • 1970-01-01
      相关资源
      最近更新 更多