Search code examples
scalaeither

Getting Value of Either


Besides using match, is there an Option-like way to getOrElse the actual content of the Right or Left value?

scala> val x: Either[String,Int] = Right(5)
scala> val a: String = x match { 
                                case Right(x) => x.toString
                                case Left(x) => "left" 
                       }
a: String = 5

Solution

  • I don't particularly like Either and as a result I'm not terribly familiar with it, but I believe you're looking for projections: either.left.getOrElse or either.right.getOrElse.

    Note that projections can be used in for-comprehensions as well. This is an example straight from the documentation:

    def interactWithDB(x: Query): Either[Exception, Result] =
      try {
        Right(getResultFromDatabase(x))
      } catch {
        case ex => Left(ex)
      }
    
    // this will only be executed if interactWithDB returns a Right
    val report =
      for (r <- interactWithDB(someQuery).right) yield generateReport(r)
    if (report.isRight)
      send(report)
    else
      log("report not generated, reason was " + report.left.get)