Functions in Groovy
Functions are central in Groovy. We’ll learn about functions with a few different examples.
When you run this Groovy script, you’ll see:
In Groovy, functions are defined using the def
keyword, followed by the function name and parameters. The return type is optional and can be omitted.
Groovy supports both explicit returns using the return
keyword and implicit returns where the last expression in the function is automatically returned.
When you have multiple parameters, you can specify their types individually. Unlike some other languages, Groovy doesn’t have a shorthand for declaring multiple parameters of the same type.
Groovy is more flexible than some languages when it comes to function calls. You can omit parentheses for function calls with at least one parameter, and you can even omit them entirely for parameterless function calls when the call is unambiguous.
There are several other features to Groovy functions. One is multiple return values, which we’ll look at next.