0

I know that arror code is an anti-pattern that we should avoid. this link: https://blog.codinghorror.com/flattening-arrow-code/

Gives several ways to fix it. However, seems it won't apply for Scala. Especially when I want to return early at the beginning of the method if some condition is not met because "return" keyword is not encouraged in Scala.

Is there an elegant way to allow me do the following in Scala?

def someFunction(): Try[MyDataType] = {
  if(some condition not met){
    // exit function
  }
  // do my actual work
}
bolei
  • 156
  • 5
  • 13
  • 1
    It seems there are already some related questions: https://stackoverflow.com/questions/38833876/how-to-early-return-in-scala https://stackoverflow.com/questions/24435800/explicit-return-from-play-action – Juan Stiza Oct 26 '17 at 19:29

1 Answers1

0

If the structure of your code is such that you have reasonably sized functionality that can be encapsulated in chunks, then I would suggest using monadic flow control to achieve the desired result:

def funcA(x: Thing): Either[FailState, NextThing] = ...
def funcB(x: NextThing): Either[FailState, NextNextThing] = ...

for{
  next <- funcA(thing)
  nextNext <- funcB(next)
  ...
} yield finalCalculation(stuff)

which will short circuit the moment one of the functions in the for-comprehension returns a Left value (since Either is now properly right biased.)

wheaties
  • 35,646
  • 15
  • 94
  • 131