Groovy - Implicit Return
Groovy methods have a capability to return last evaluated value without explicit return statement. This feature is termed as implicit return. It is a syntactic sugar to make code more consise especially in case, a operation is returning a last evaluated expression.
What is Implicit Return
In most of the popular programming languages, we need to use return keyword to specify that a method should send a value to the caller. Groovy is one step ahead. It don't need to use return keyword explicitly. The last expression evaluated of the method called is automatically returned. Consider the following example −
Example.groovy
def multiply(int a, int b) {
a * b
}
def result = multiply(5, 3)
// prints 15
println result
Output
When we run the above program, we will get the following result.
15
Here the last line of multiply() method is implicitly returned when the method is called.
Example - Use of return statement explicitly
We can use return statement explicitly in case we need to return a value earlier instead at the end of the method. Or as per preference, we can use return statement.
Example.groovy
def checkNumber(int num) {
if (num < 0) {
return "Negative"
}
"Positive or Zero"
}
// prints Negative
println checkNumber(-2)
// Output: Positive or Zero
println checkNumber(5)
Output
When we run the above program, we will get the following result.
Negative Positive or Zero
Key Considerations
Last Expression Only − Value of last evaluated expression only is implicitly returned. To return other statements, explicit return statement is to be used.
Conciseness − Implicit return although make code concise, but in case of multiple statements, explicit return statement is better in terms of readablity. For consistency of code, explicit returns are more preferred.
Closure − Closure exhibits implicit return. The last expression is automatically returned in a closure.