1
votes

I have a code returning Future[String \/ Response], monad instances for both Disjunction and Future and function getResult: Response => [String \/ Result]. Now this is written with several nested functions and I want to see it as following

for {
  response <- getResponse
  result <- getResult(response)
} yield result   // Future[String \/ Result]

As I can understand Monad transformers are using exactly for this purpose and I could do similar things if I had Option instead of \/. But unfortunately I couldn't found FutureT nor DisjunctionT (although XorT exists for cats).

So, is it possible to write monad transformer for above purpose? May be it already exist or I don't understand something.

1

1 Answers

3
votes

You can use scalaz.EitherT to combine the effects of \/ (Disjunction) and another monad, in your case Future.

def getResponse: Future[String \/ Response] = ???
def getResult(resp: Reponse): Future[String \/ Result] = ???

(for {
  response <- EitherT(getResponse)
  result <- EitherT(getResult(response))
} yield result).run
// Future[String \/ Result]

Or you could change the return types of the getResponse and getResult functions to return EitherT :

type R[A] = EitherT[Future, String, A]

def getResponse: R[Response] = ???
def getResult(resp: Reponse): R[Result] = ???

(for {
  response <- getResponse
  result <- getResult(response)
} yield result).run
// Future[String \/ Result]