Anonymous Human
Anonymous Human

Reputation: 1948

multiple return syntax

I have a function that returns multiple values like this:

def func1() {
    return [val1, val2]
}

How do I go about assigning these return values to another variable in the function that calls this function. I imagine it would be something like:

def funcThatCalledfunc1 {
    def [x,y] = func1()
}

I want to end up x having value of val1 and y having value of val2.

Upvotes: 10

Views: 8423

Answers (2)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

If you are trying to use Groovy's multiple assignment, you can do something like this:

def func1 = {
    ['jeff', 'betsy', 'jake', 'zack']
}

def (dad, mom, son1, son2) = func1()

assert 'jeff' == dad
assert 'jake' == son1
assert 'zack' == son2
assert 'betsy' == mom

In your example you used square brackets instead of parens, which will not work.

Upvotes: 19

Joshua Moore
Joshua Moore

Reputation: 24776

The simplest way to accomplish this is to expect the return value to be a list and access the return values by index. I personally would use a map because it's less fragile.

def func1 {return [val1, val2]}
def result = func1()
def x = result[0]
def y = result[1]

Here is an example using a map instead:

def func1 {return [x: val1, y: val2]}
def result = func1()
def x = result['x']
def y = result['y']

Upvotes: 3

Related Questions