Is the use of exceptions a bad practice in scala?

前端 未结 3 622
鱼传尺愫
鱼传尺愫 2021-02-02 11:04

I\'ve seen many times pieces of scala code using Option (for simple values) or Either[List[Error], T] for handling errors.

this gives place to code like this

         


        
3条回答
  •  北海茫月
    2021-02-02 11:22

    The following version uses the fact that the right projection of Either is a monad, and is exactly equivalent to your code:

    def createApplicationToken(accessToken: AccessToken) = for {
       info <- retrieveProviderInfo(accessToken).right
       user <- User.findOrCreateFromProviderInfo(info).right
       refr <- user.refreshApplicationToken.right
    } yield refr.token
    

    And does a much better job of showing off the advantages of Either.

    More generally, the rules are the same as in Java: use exceptions for exceptional situations. You just might find that you change your definition of exceptional a bit when you're working in this style—e.g., invalid user input isn't really exceptional, a timed-out network request isn't really exceptional, etc.

    Right-biased Either since Scala 2.12

    You can now omit .right, so the following code is equivalent since Scala 2.12:

    def createApplicationToken(accessToken: AccessToken) = for {
       info <- retrieveProviderInfo(accessToken)
       user <- User.findOrCreateFromProviderInfo(info)
       refr <- user.refreshApplicationToken
    } yield refr.token
    

提交回复
热议问题