What are the differences between Either and Option?

前端 未结 2 887
挽巷
挽巷 2021-02-05 18:22

According to the documentation:

A common use of Either is as an alternative to Option for dealing with possible missing values.

W

2条回答
  •  無奈伤痛
    2021-02-05 18:45

    Either can be seen as a generalization of Option. If you fix the first value of Either, for example by setting it to Unit, you would get something that behaves in essentially the same way as Option:

    Option[X] := Either[Unit, X]
    

    In this case, Left[Unit, X] would correspond to None, and Right[Unit, X] would correspond to Some[X].

    For Option[X], None would signal some kind of failure to obtain a value of type X, and Some[X] would signal success. For Either[Unit, X], instance of type Left[Unit, X] would represent failure, and Right[Unit, X] would represent success.

    However, you can use the first component of Either to store more detailed information about why something failed, or some additional information that helps you to recover from an error. Option gives you just a None, which is not very useful. But Either[F,X] could return either a success value Right[F, X], which is essentially just a wrapper for X, or a detailed description of failure in Left[F, X], with a value of type F representing the failure.

    This allows you to define more sophisticated recovery strategies. For example, take a look at Form.scala of the Play!-Framework. They use Either all over the place, because they want to either respond to user's form submission, or to send back a partially filled form, annotated with helpful error messages. The alternative to this would be to work with Option[TypeOfFormContent], which would evaluate to None if some of the form fields contained invalid input. This in turn would mean that the user gets something like "Bad Request. Please fill the whole form again." as response, which would be utterly annoying. Therefore, Either is used instead of Option, because it can actually keep track of what exactly went wrong with the form submission.

    The disadvantage of Either is that it is not a monad: in order to work with it effectively, you always have to pass two different callbacks for the two different cases. This can result in a "callback-hell". Therefore, one should think carefully whether an exact description of the failure is that valuable. In the case of a failed form submission, a detailed description of the failure is valuable, because one does not want to force the user to retype everything again. In other cases, Option might be more appropriate, because one does not want to force the programmers to deal with unnecessary detailed descriptions of unrecoverable errors.

提交回复
热议问题