Multi-Option Type in Scala

How can I archive a type of type Option, which either returns something of type T, or of type Error?

I make several web requests, and the answers are either "good" or contain an object, or the call returns an error, in which case I want to provide an Error object with the cause of the error.

So something like:

def myRequest() : Result[MyObject] {
  if (thereWasAnError) Error(reason) else MyObject 
}
+5
source share
1 answer

scala.Either

Either the type should be exactly what you want:

def myRequest() : Either[String, MyObject] = 
    if (thereWasAnError) 
        Left("Some error message") 
    else 
        Right(new MyObject)

Eithersimilar to Option, but may contain one of two possible values: left or right. By agreement, the right is in order, and on the left - an error.

Now you can make some fancy patterns:

myRequest() match {
    case Right(myObject) =>
        //...
    case Left(errorMsg) =>
        //...
}

scala.Option.toRight()

Similarly, you can use Optionand translate it to Either. Since usually *right* values is used for success and left for failure, I suggest usingtoRight () rather thantoLeft () `:

def myRequest() : Option[MyObject] =
    if (thereWasAnError)
        None
    else
        Some(new MyObject)

val result: Either[String, MyObject] = myRequest() toRight "Some error message"

Either .

+14

All Articles