Either left or right
Scala has an Either[+A, +B] type for us. But before we talk about Either, let's use it. We'll refactor our code with the Either type:
import java.lang.Exception
import scala.util.{Failure, Success, Try}
object Main extends App {
def toInt(str: String): Either[String, Int] = Try(str.toInt) match {
case Success(value) => Right(value)
case Failure(exp) => Left(s"${exp.toString} occurred," +
s" You may want to check the string you passed.")
}
println(toInt("121"))
println(toInt("-199"))
println(toInt("+ -199"))
} The following is the result:
Right(121) Right(-199) Left(java.lang.NumberFormatException: For input string: "+ -199" occurred, You may want to check the string you passed.)
In the preceding code, we knew things might go wrong with the conversion from a string to an int. So the result can be either an exception or the intended integer. So we tried to do the same: we used the Either type with the left value as a String...