Suppose we want to implement a function that checks whether the length of a string is within certain limits. If the check succeeds the function shall return the provided value, if it fails some information about the reason shall be returned.
We can meet these requirements by using Either as the return type of the function:
import scala.util.{Either, Left, Right}
def checkString(value: String): Either[String, String] = {
val len = value match {
case s: String => s.length
case _ => 0
}
len match {
case _ if (len < 4) => Left("too short")
case _ if (len > 10) => Left("too long")
case _ => Right(value)
}
}
checkString("user") match {
case Right(value) => println(s"valid value: $value")
case Left(reason) => println(s"invalid value: $reason")
}
n
This, of course, works fine but the naming of Left and Right has not much semantic to it and a caller of checkString always has to consult the documentation to know what kind of result Left and Right represent.
To make things clearer I propose to add a type Result to the Scala Standard Library which has concrete implementations named Ok and Err. Since Success and Failure are aready used by scala.util.Try I suggest to just take the names of the corresponding Rust enum values.