Scala - How to Combine EitherT with Either in For Comprehension

孤街醉人 提交于 2019-12-19 11:52:11

问题


Suppose I have the following setting:

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

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)

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...

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


回答1:


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)


来源:https://stackoverflow.com/questions/52086992/scala-how-to-combine-eithert-with-either-in-for-comprehension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!