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 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.
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.
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.
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.
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 using
toRight()rather than
toLeft()`:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With