Multiple return points in scala closure/anonymous function
        Posted  
        
            by Debilski
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Debilski
        
        
        
        Published on 2010-05-24T17:27:05Z
        Indexed on 
            2010/05/24
            17:31 UTC
        
        
        Read the original article
        Hit count: 383
        
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.)
© Stack Overflow or respective owner