Search code examples
scalascala-cats

Scala - How to Combine EitherT with Either in For Comprehension


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?


Solution

  • 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)