I'm interested in knowing the design decisions why scala.Either
was not done as a monad. There already exists some discussion on how to right-biasing Either
, for example:
But there are mentioned too much details and I couldn't get an complete overview about why it is done as it is done. Can someone give an overview about the benefits of having a right-biased Either
, about the problems to do it that way and about the benefits of not having an right-biased Either
(if they even exist)?
Monad in scala are a category of data types. Informally, anything that has a type parameter, a constructor that takes an element of that type, and a flatMap method (which has to obey certain laws) is a monad. A monad is a mechanism for sequencing computations.
In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared.
I think it just comes down to the Principle of Least Astonishment. Using Either
to encode success or failure is clearly something people do, but it is not the only use of Either
. In fact, there is not much reason to have Right
be success and Left
be failure other than tradition. As adelbertc's comment above mentions, scalaz has Validation
which specifically encode this.
To further justify the POLA claim above, take this code:
def foo(): Either[Int, Int] = Right(1)
def bar(j: Int): Either[Int, Int] = Left(1)
def baz(z: Int): Either[Int, Int] = Right(3)
// Result is Left(1)
for (a <- foo().right; b <- bar(a).right; c <- baz(b).right) yield c
This compiles because I am using the .right
projection in the for
expression. It makes sense here the Left(1)
in bar
is the failure case and so that is the result, but imagine if Either
was Right
-biased. The above code would compile without the .right
projections in the expression like:
for (a <- foo(); b <- bar(a); c <- baz(b)) yield c
If you used Either
in your code to just be a "one-or-the-other" type, you would be surprised by (1) the fact that this would compile and (2) that it returns Left(1)
and seemingly never executes baz
.
In summary, use Validation
if you want to use Either
to encode success or failure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With