Multiple Return Syntax

I have a function that returns multiple values:

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

How do I assign these return values ​​to another variable in the function that calls this function. I assume it will be something like:

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

I want to end xwith value val1and ywith value val2.

+4
source share
2 answers

If you are trying to use Groovy 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.

+9
source

- , . , .

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

:

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

Source: https://habr.com/ru/post/1547474/


All Articles