Michael
Michael

Reputation: 42110

Return codes in Scala

Suppose I am writing a function in Scala, which returns a return code: SUCCESS, ERROR1, ERROR2, ... (note that is different from scala.util.Either)

Obviously, I can create an hierarchy to represent the return code as follows:

trait ReturnCode
case object Success extends ReturnCode
case object Error1 extends ReturnCode
case object Error2 extends ReturnCode
...

Now I wonder if there is a "standard" idiomatic solution in Scala for that.

Upvotes: 0

Views: 492

Answers (2)

drexin
drexin

Reputation: 24403

You can use Try, as an alternative to Either. The "left" value is fixed to Throwable and it is right-biased, which means, that map/flatMap etc will only be executed on a success and exceptions are kept as they are, just like wirh Some and None for Option. You can use Try.apply around a block to catch non fatal exceptions and wrap the result in a Try.

Upvotes: 3

senia
senia

Reputation: 38045

You could use sealed keyword.

sealed trait ReturnCode
case object Success extends ReturnCode
case object Error1 extends ReturnCode
case object Error2 extends ReturnCode

You'll get a warning if you'll forget some of codes:

scala> def test(r: ReturnCode) = r match {
     |   case Success => "Success"
     |   case Error1 => "Error1"
     | }
<console>:1: warning: match may not be exhaustive.
It would fail on the following input: Error2
       def test(r: ReturnCode) = r match {

Upvotes: 2

Related Questions