How can I archive a kind of Option type which either returns something of type T or of type Error?
I am doing some web requests and the responses are either “ok” and contain the object or the call returns an error, in which case I want to provide an Error object with the reason of error.
So something like:
def myRequest() : Result[MyObject] {
if (thereWasAnError) Error(reason) else MyObject
}
scala.EitherEithertype should be exactly what you want:Eitheris similar toOptionbut can hold one out of two possible values: left or right. By convention right is OK while left is an error.You can now do some fancy pattern matching:
scala.Option.toRight()Similarily you can use
Optionand translate it toEither. Since typically*right* values is used for success and left for failure, I suggest usingtoRight()rather thantoLeft()`:However returning
Eitherdirectly as a result ofmyRequest()seems more straightforward in this simple example.