Getting Value of Either

前端 未结 4 1164
长情又很酷
长情又很酷 2021-01-01 11:54

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



        
4条回答
  •  难免孤独
    2021-01-01 12:13

    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)
    

提交回复
热议问题