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
.
You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas.
No, you can not have two returns in a function, the first return will exit the function you will need to create an object.
Java doesn't support multi-value returns.
You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With