Scala: How to return a result code in a concise way

def processRequest(userId: UUID, requestId: UUID): BusinessResult
public enum BusinessResult
{
Ok, UserNotFound, RequestNotFound, NotOwner
}

Java-style

The old-school implementation of this method would be:

  • Very clear to a reader (even for unfamiliar with Scala)
  • In Scala World it’s uncommon to use return keyword
  • Also using of Option.get function is uncommon and considered as a bad practice mostly

Use exceptions internally

Another solution is to use exceptions:

  • More concise
  • Not using Option.get function
  • You may extract the code without try..catch and use it for a transition to exception-based error control (if you’re going to that transition)
  • Usage of exceptions without actual need

Scala collections

I tried to realize, how to use collections API for such tasks, i.e. using Option.fold method:

Either FTW

The common use case for Either is a replacement for Option where None will contain some meaningful value (by convention it’s Left).

Adding some implicit magic…

With some implicit “magic” we can transform this code to a bit more concise form:

Conclusion

So, we made a path from old-school Java-style to a concise Scala-style for such scenario of error handling: less verbosity, no ifs.

--

--

Software developer, moved to Israel from Russia, trying to be aware of things.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dmitry Komanov

Dmitry Komanov

Software developer, moved to Israel from Russia, trying to be aware of things.