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?
In Groovy we can omit the return keyword at the end of a method, it is optional. It is no problem to leave it in, but we can leave it out without any problems.
The if's condition needs to be an expression. Assertions are for cases where you want it to fail loudly if what you're asserting is not true. Don't use assert unless you want it to throw an exception if the condition is not met.
The groovy string method toBoolean() converts the string value to a boolean value. The toBoolean() documentation says: If the trimmed string is "true", "y" or "1" (ignoring case) then the result is true otherwise it is false.
The page you linked (rather tersely) describes the exact semantics:
Notice that the return statement is optional at the end of methods.
So the b
in that if
block 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 were
def append(a, b) {
if (!a) { b }
else { a + b }
}
Then the result would be b
if !a
is true
and a + b
otherwise.
The result of a call to a void
function is null
, so if the example were
def append(a,b) {
if (!a) { b }
else { a + b }
println "debug: $a $b"
}
Then append
would always return null
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With