Either, Try, and Validation in Scala
Asked Answered
A

1

7

I am confused with Either, Try, and Validation of scalaz. None of them seems to do what I need. What I need is a simple monad Result[E, R] where E is an error type and R is an result type.

  • Either is not suitable because it is not a monad (but the projections are) and unbiased.
  • Try is not suitable since its error type is Throwable and it is not exactly a monad
  • Validation is not a monad at all.

What would you suggest ? Should I write this Result type by myself ?

Algia answered 13/3, 2014 at 12:24 Comment(3)
Use Either projections.Tenor
Why are Try not monads ? What monad laws does it break ?Garnishee
@Garnishee - Try breaks the unit law in favor of safety, only in the case where an exception is thrown. If you have f: A => Try[B], then Try(a).flatMap(f) has identical behavior to f(a) according to the unit law. But if f(a) throws an exception, Try's flatMap will catch it. Hence, in case of exception Try is non-monadic because monadicity is irreconcilable with safety from exceptions. Since the point of Try is exception-safety, it favors safety. (If you restrict yourself to inputs that do not throw exceptions, Try is a monad.)Indisputable
H
8

If you're willing to use Scalaz (and it sounds like you are), \/ (usually pronounced "disjunction") is exactly what you're looking for—a monadic, right-biased version of Either.

It also includes lots of other nice stuff you don't get with the right projection of Either in the standard library (1.right syntax, combinators like +++, converters from Validation, etc.).

Hallam answered 13/3, 2014 at 13:3 Comment(1)
Yep, although it's now deprecated in favor of the even-more-awkwardly-named \/.fromTryCatchThrowable.Hallam

© 2022 - 2024 — McMap. All rights reserved.