In Groovy, the return statement is optional, allowing you to write methods like:
def add(a, b) {
a + b
}
…which adds a and b and returns the result to the caller.
However, I’m wondering what the semantics are when the method has multiple return “statements”. For example, in Java you might have:
String append(String a, String b) {
if (a == null) {
return b;
}
return a + b;
}
This could (hypothetically) be translated to Groovy like:
def append(a, b) {
if (! a) {
b
}
a + b
}
However, in this case, how does Groovy know that b inside of the if statement should be returned? Or does it not? I assume that Groovy cannot simply treat any statement whose result is unused as a return, correct? Are there any clearly defined semantics for how the “optional return” feature behaves in this case?
The page you linked (rather tersely) describes the exact semantics:
So the
bin thatifblock would never be returned unless you explicitly returned it. In practice this means that the return value will be the result of the last statement evaluated, so if your example wereThen the result would be
bif!aistrueanda + botherwise.The result of a call to a
voidfunction isnull, so if the example wereThen
appendwould always returnnull.My own rule of thumb for this is to always use an explicit return statement if the method or closure contains more than one statement. I think relying on the implicit return statement in more complex methods is dangerous since if anyone adds a line to the end of the method they will change the return value even though they most likely didn’t intend to.