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 .