Return statements
Scala allows using return statements in order to return from methods early. However, Scala is primarily an expression-based language, therefore using imperative constructs like returns usually hurts readability.
Moreover, return
statements are always bound to the enclosing def
, therefore, if return
is used e.g. inside a closure, it results in a try/catch
for a NonLocalReturnControl
exception generated by the compiler.
The general rule is to avoid using return
s, however, there are cases when they do increase the clarity of the code. Therefore, whether they are appropriate or not should be decided on a case-by-case basis during code review. Basically, return
is allowed for the following cases:
// As a guard to simplify the control flow:
def doSomething(input: String): String = {
if (!valid(input)) {
return "something went wrong"
}
...
}
// As an early return from loops
while (condition) {
if (somethingHappened) {
return
}
}