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 ...

Get Learning Scala Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.