O'Reilly logo

Learning Scala Programming by Vikash Sharma

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required