Using Either to process failures in Scala code

后端 未结 4 899
陌清茗
陌清茗 2020-11-28 03:27

Option monad is a great expressive way to deal with something-or-nothing things in Scala. But what if one needs to log a message when \"nothing\" occurs? Accord

4条回答
  •  长情又很酷
    2020-11-28 04:04

    Either is used to return one of possible two meaningful results, unlike Option which is used to return a single meaningful result or nothing.

    An easy to understand example is given below (circulated on the Scala mailing list a while back):

    def throwableToLeft[T](block: => T): Either[java.lang.Throwable, T] =
      try {
        Right(block)
      } catch {
        case ex => Left(ex)
      }
    

    As the function name implies, if the execution of "block" is successful, it will return "Right()". Otherwise, if a Throwable is thrown, it will return "Left()". Use pattern matching to process the result:

    var s = "hello"
    throwableToLeft { s.toUpperCase } match {
      case Right(s) => println(s)
      case Left(e) => e.printStackTrace
    }
    // prints "HELLO"
    
    s = null
    throwableToLeft { s.toUpperCase } match {
      case Right(s) => println(s)
      case Left(e) => e.printStackTrace
    }
    // prints NullPointerException stack trace
    

    Hope that helps.

提交回复
热议问题