Here’s a little titbit from GridGain’s Scalar DSL code:
Not frequently – but often enough – we have the following code in Scala:
def func() {
if (this) {
doThat()
return
}
...
if (that) {
doThis()
return
}
...
}
You get the picture… It’s not kosher to put the code like that into Scala compiler
Now, in some cases the algo can be rework to remove multiple returns, but in other cases this simply isn’t possible without unnecessary complicating the code. In other words, trade offs are not worth it.
So, for case where algo can’t be changed we’ve come up with a simple “cleaning” solution in a way of a “pimp” for Unit type using Scala’s scala.util.control.Break support:
implicit def f(v: Unit) = new { def ^^ = break }
Once you have that “pimp” in the scope you can rewrite previous example like this:
def func() = breakable {
if (this) doThat() ^^
...
if (that) doThis() ^^
...
}
Few comments:
- Operator
^^ has a nice visual connotation of exiting the function and code gets shorter which never hurts.
^^ is also unique enough so that unlikely naming conflicts won’t confuse the compiler.
- It enables user-defined scopes while simple
return always defaults to the scope of the entire method.
This is, of course, more of a “’cause I can” type of the solution but nonetheless represents great flexibility of the Scala language.
Enojy!