Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Option type in Scala

Tags:

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 
}
like image 387
user3001 Avatar asked May 28 '12 12:05

user3001


People also ask

What is option type in scala?

Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value.

What is isDefined in scala?

Definition Classes IterableOps.  final def isDefined: Boolean. Returns true if the option is an instance of scala. Some, false otherwise. Returns true if the option is an instance of scala.Some, false otherwise.

What is getOrElse in scala?

As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.

What is some () in scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some. We can use this with the collection.


1 Answers

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.

like image 119
Tomasz Nurkiewicz Avatar answered Oct 23 '22 15:10

Tomasz Nurkiewicz