Beginning in Scala and reading about Either
I naturally comparing new concepts to something I know (in this case from Java). Are there any differences from the
Yes, Either
is a way to embed exceptions in a language; where a set of operations that can fail can throw an error value to some non-local site.
In addition to the practical issues Rex mentioned, there's some extra things you get from the simple semantics of an Either
:
Either
forms a monad; so you can use monadic operations over sets of expressions that evaluate to Either
. E.g. for short circuiting evaluation without having to test the result Either
is in the type -- so the type checker alone is sufficient to track incorrect handling of the valueOnce you have the ability to return either an error message (Left s)
or a successful value Right v
, you can layer exceptions on top, as just Either
plus an error handler, as is done for MonadError in Haskell.