views:

187

answers:

4

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 ifelse 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.

+1  A: 

If your anonymous function's that complex, I'd make it more explicit. Anonymous functions are not suited to anything more complex than a few lines. You could make it method private by declaring it within the using method

def myF(i:Int):Int = {
    if (i%2 == 0) return i
    doMoreStuffAndReturnSomething(i)
}
someList.map(myF(_))

This is a variation on your workaround, but is cleaner. They both keep it private to the local method scope.

sblundy
+3  A: 

In your code comment, you wrote that you want to avoid the else keyword, but IMHO this does exactly what you want and its even two characters shorter ;-)

someList.map((i) => {
    if (i%2 == 0) i else
    doMoreStuffAndReturnSomething(i)
})
Michel Krämer
Please see my edit.
Debilski
Actually, I’d say that it saves more than two characters: An explicit `return` forces you to declare the return type anyway… However my actual use case would be a little more complicated than the example I originally gave, so it’s not just about saving characters.
Debilski
+3  A: 

The example you've given is easily solved by an if statement. There are no performance or other penalties for doing this.

But you might have some other situation, which looks roughly like

if (test) {
  if (anotherTest) {
    val a = someComputation()
    if (testOf(a)) return otherComputation()
  }
  else if (yetAnotherTest) return whatever()
}
bigComputation()

There are a few ways to deal with this sort of situation if you want to avoid the tangle of if-statements and/or code duplication needed to convert this to a form without returns.

There are various sneaky things you can do with Option or Either to keep state flowing along (with orElse and fold) so that you do only the computations you need to.

You're really better off creating a def as you suggest. But just to compare, consider an Option-wrapping style:

i => {
  ( if ((i%2)==0) Some(i) 
    else None
  ).getOrElse(doStuffAndReturn(i))
}

On the large example above, this style would give

( if (test) {
    if (anotherTest) {
      val a = someComputation()
      if (testOf(a)) Some(otherComputation()) else None
    }
    else if (yetAnotherTest) Some(whatever())
    else None
}).getOrElse(bigComputation())

Personally, I don't think it's clearer (and it's certainly not faster), but it is possible.

Rex Kerr
Yeah, it’s as convoluted (or slightly more even) as the original example without returns. But of course it’s a valid approach in other situations.
Debilski
A: 

I think the main problem with return points in anonymous functions is that an anonymous function might spring up at a place where one normally wouldn’t expect it. So, it wouldn’t be clear which closure the return statement would actually belong to. This problem is solved by explicitly requiring a defreturn* correspondance.

Alternatively, one would need guards around the statement from which to return. breakablebreak but unfortunately can’t return a value with that. Some continuation based solutions would be able to reach that goal, though I’d like to wait for some general acceptance and libraries there.

Debilski