scalascalaztwitter-finagle

Map or match a Scalaz.EitherT


I have this for-comprehension:

 val seq = for {
        accessToken <- EitherT(getAccessToken(code))
        data <- EitherT(getDefaultData(accessToken))
        user <- EitherT(mapUser(data.getResponseBody))
      } yield {
        if (Users.getUserByOriginId(user.origin).isEmpty) {
          Users.register(user)
          OAuthProvider.redirectToSignUp(user.userId.get)
        } else {
          OAuthProvider.redirectToAuthentication(user.userId.get)
        }
      }

It chains com.twitter.util.Future operations, each of the methods returning a Future[\/[InvalidResponse, CorrectResponse]]

I now want to map or match over the result.

val response = seq.run match {
    case x.left => "something"
    case y.right => "something else"
}// this syntax is invalid

What is the correct syntax to match between left and right?


Solution

  • The match syntax is

    val response = seq.run.map{fut => fut.match {
          case -\/(left) => "something"
          case \/-(right) => "something else"
      }
    }
    

    You can also do fold/catamorphism on the EitherT:

    seq.fold(something, somethingElse)
    

    where something takes a value of left type & returns a value of type X and somethingElse takes a value of right type and returns a value of type X. The result of the entire expression being Future[X]