Multiple Return Values in Groovy

Groovy has built-in support for multiple return values, similar to the original example. This feature is often used in idiomatic Groovy, for example to return both result and error values from a function.

// The def keyword in Groovy is used to define a method that returns multiple values
def vals() {
    return [3, 7]
}

// In the main method, we demonstrate how to use multiple return values
static void main(String[] args) {
    // Here we use the multiple return values from the call with multiple assignment
    def (a, b) = vals()
    println(a)
    println(b)

    // If you only want a subset of the returned values,
    // you can use the underscore (_) as a placeholder
    def (_, c) = vals()
    println(c)
}

To run the program, save it as MultipleReturnValues.groovy and use the groovy command:

$ groovy MultipleReturnValues.groovy
3
7
7

In Groovy, multiple return values are typically implemented using lists or arrays. The syntax for destructuring assignment (like def (a, b) = vals()) allows us to easily assign multiple returned values to individual variables.

The underscore (_) in Groovy, similar to the blank identifier in the original example, can be used as a placeholder when you want to ignore certain returned values.

Groovy’s approach to multiple return values provides a flexible and readable way to handle functions that need to return more than one value, which can be particularly useful for error handling or when a function naturally produces multiple results.