Is Either the equivalent to checked exceptions?

后端 未结 3 1847
抹茶落季
抹茶落季 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:53

    Either is equivalent to a checked exception in terms of the return signature forming an exclusive disjunction. The result can be a thrown exception X or an A. However, throwing an exception isn't equivalent to returning one – the first is not referentially transparent.

    Where Scala's Either is not (as of 2.9) equivalent is that a return type is positively biased, and requires effort to extract/deconstruct the Exception, Either is unbiased; you need to explicitly ask for the left or right value. This is a topic of some discussion, and in practice a bit of pain – consider the following three calls to Either producing methods

    for {
      a <- eitherA("input").right
      b <- eitherB(a).right
      c <- eitherC(b).right
    } yield c // Either[Exception, C]
    

    you need to manually thread through the RHS. This may not seem that onerous, but in practice is a pain and somewhat surprising to new-comers.

提交回复
热议问题