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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.