score:4

Accepted answer

If you are into using Either you could do the following. It looks nicer, if it is understandable depends on how at ease you are with either.

val either = for {
  y <- f1(x).toRight(error1).right
  z <- f2(y).toRight(error2).right
} yield ok(z)

either.merge

Some background:

Option.toRight converts to a Right (success case) if the option is defined, otherwise returns a Left of the argument (error case).

Either.right projects the Either to the right, i.e. monadic operations are such that Right is Some, Left is None, but it preserves the Left value if we are in the left case.

Either.merge works only on Either[A, A] and returns whatever value is in the Left or the Right.


Related Query