Using Free Monad with Either

405 views Asked by At

I have two DSLs - EmployeeAction and ContactAction. Here are my traits (Actions)

Complete Gist: link

sealed trait EmployeeAction[R]
case class GetEmployee(id: Long) extends EmployeeAction[Either[Error, Employee]]

sealed trait ContactAction[R]
case class GetAddress(empId: Long) extends ContactAction[Either[Error, Address]]

I've used cats' Coproduct and Inject here is my program to get manager's address:

type Program = Coproduct[EmployeeAction, ContactAction, A]

def findManagerAddress(employeeId: Long)
               (implicit EA: EmployeeActions[Program],
                CA: ContactActions[Program]): Free[Program, Address] = {
  import EA._, CA._
  for {
    employee <- getEmployee(employeeId)
    managerAddress <- getAddress(employee.managerId)
  } yield managerAddress
}

The above doesn't compile because getEmployee returns an Either[Error, Employee]. How do I handle this in Free for comprehension?

I tried wrapping up with EitherT monad transformer as below, it shows no errors in IntelliJ but it fails upon building.

for {
  employee <- EitherT(getEmployee(employeeId))
  managerAddress <- EitherT(getAddress(employee.managerId))
} yield managerAddress

Below is the error:

[scalac-2.11] /local/home/arjun/code/Free/src/FreeScalaScripts/src/free/program/Program.scala:71: error: no type parameters for method apply: (value: F[Either[A,B]])cats.data.EitherT[F,A,B] in object EitherT exist so that it can be applied to arguments (cats.free.Free[free.Program,Either[free.Error,free.Employee]])
[scalac-2.11]  --- because ---
[scalac-2.11] argument expression's type is not compatible with formal parameter type;
[scalac-2.11]  found   : cats.free.Free[free.Program,Either[free.Error,free.Employee]]
[scalac-2.11]  required: ?F[Either[?A,?B]]
[scalac-2.11]       employee <- EitherT(getEmployee(employeeId))
[scalac-2.11]                   ^

How do I deal with Either in for comprehension and how to propagate the errors to the caller? I want to know for which all employee ids the call failed.

1

There are 1 answers

1
Ziyang Liu On

EitherT takes a F[Either[A, B]] but you have a Free[Program, Either[Error, Employee]], which is not compatible.

The solution to create a type alias for Free[Program, A]:

type MyAlias[A] = Free[Program, A]

Then make getEmployee return MyAlias[Either[Error, Employee]] and same for getAddress.