Is Either the equivalent to checked exceptions?

后端 未结 3 1849
抹茶落季
抹茶落季 2021-02-19 08:14

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

3条回答
  •  不知归路
    2021-02-19 08:54

    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 value

    Once 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.

提交回复
热议问题