Functions in Groovy

Functions are central in Groovy. We’ll learn about functions with a few different examples.

// Here's a function that takes two integers and returns
// their sum as an integer.
def plus(int a, int b) {
    return a + b
}

// In Groovy, the last expression in a function is automatically
// returned, so we can omit the 'return' keyword if we want.
def plusPlus(int a, int b, int c) {
    a + b + c
}

// The main method is the entry point of the program
static void main(String[] args) {
    // Call a function just as you'd expect, with name(args).
    def res = plus(1, 2)
    println("1+2 = ${res}")

    res = plusPlus(1, 2, 3)
    println("1+2+3 = ${res}")
}

When you run this Groovy script, you’ll see:

$ groovy functions.groovy
1+2 = 3
1+2+3 = 6

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.