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
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.
Either
since Scala 2.12You 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