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("+ -199")) 

The following is the result:

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 live online training, plus books, videos, and digital content from nearly 200 publishers.