Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple return syntax

Tags:

groovy

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.

like image 647
Anonymous Human Avatar asked Jul 07 '14 18:07

Anonymous Human


People also ask

How can I return multiple values?

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.

Can you have 2 returns in a function?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.

Can you have 2 returns in Java?

Java doesn't support multi-value returns.

Can we return 2 variables?

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.


2 Answers

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.

like image 131
Jeff Scott Brown Avatar answered Dec 04 '22 09:12

Jeff Scott Brown


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']
like image 29
Joshua Moore Avatar answered Dec 04 '22 09:12

Joshua Moore