user3001
user3001

Reputation: 3497

Multi-Option type in Scala

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 
}

Upvotes: 5

Views: 2351

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

scala.Either

Either type should be exactly what you want:

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

Either is similar to Option but 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:

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

scala.Option.toRight()

Similarily you can use Option and translate it to Either. Since typically *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"

However returning Either directly as a result of myRequest() seems more straightforward in this simple example.

Upvotes: 14

Related Questions