本文介绍了Scala - 如何结合EitherT和Either in For Comprehension的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下设置:

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

如何使用理解来实例化 Baz 类?我试过:

How can I use for comprehension to instantiate the class Baz? I tried with:

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

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

but, the result has type Either[Error, Nothing]. I don't know what is the right return type in this case, but obviously I don't want Nothing...

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

What is the right way to combine Either and EitherT in for comprehension?

推荐答案

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

Use EitherT.fromEither function to create EitherT from Either

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)

这篇关于Scala - 如何结合EitherT和Either in For Comprehension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:13