Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiple return points in scala closure/anonymous function
    text
    copied!<p>As far as I understand it, there is no way in Scala to have multiple return points in an anonymous function, i.e.</p> <pre><code>someList.map((i) =&gt; { 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 }) </code></pre> <p>raises an <code>error: return outside method definition</code>. (And if it weren’t to raise that, the code would not work as I’d like it to work.)</p> <p>One workaround I could thing of would be the following</p> <pre><code>someList.map({ def f(i: Int):Int = { if (i%2 == 0) return i doMoreStuffAndReturnSomething(i) } f }) </code></pre> <p>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?</p> <p>(A use case would be to emulate some valued <code>continue</code> construct inside the loop.)</p> <p><strong>Edit</strong></p> <p>Please believe me, that there is a need for avoiding the else statement, because, the <code>doMoreStuff</code> part might actually look like:</p> <pre><code>val j = someCalculation(i) if (j == 0) return 8 val k = needForRecalculation(i) if (k == j) return 9 finalRecalc(i) ... </code></pre> <p>which, when you only have an <code>if</code>–<code>else</code> structure available gets easily messed up.</p> <p>Of course, in the simple example I gave in the beginning, it is easier to just use <code>else</code>. Sorry, I thought this was clear.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload