Multiple return points in scala closure/anonymous function
- by Debilski
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)
})
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.)