As far as I understand it, there is no way in Scala to have multiple return points in an anonymous function, i.e.
someList.map((i) => {
if (i%2 == 0) return i // the early return allows me to avoid the else clause
doMoreStuffAndReturnSomething(i) // thing of this being a few more ifs and returns
})
raises an error: return outside method definition
. (And if it weren’t to raise that, the code would not work as I’d like it to work.)
One workaround I could thing of would be the following
someList.map({
def f(i: Int):Int = {
if (i%2 == 0) return i
doMoreStuffAndReturnSomething(i)
}
f
})
however, I’d like to know if there is another ‘accepted’ way of doing this. Maybe a possibility to go without a name for the inner function?
(A use case would be to emulate some valued continue
construct inside the loop.)
Edit
Please believe me, that there is a need for avoiding the else statement, because, the doMoreStuff
part might actually look like:
val j = someCalculation(i)
if (j == 0) return 8
val k = needForRecalculation(i)
if (k == j) return 9
finalRecalc(i)
...
which, when you only have an if
–else
structure available gets easily messed up.
Of course, in the simple example I gave in the beginning, it is easier to just use else
. Sorry, I thought this was clear.