How to take multiple parameters from returned function in groovy

I want to return some values ​​from a function written in groovy and get them, but I get an error

class org.codehaus.groovy.ast.expr.ListExpression, with its value '[a, b]', is a bad expression on the left side of the job

My code

int a=10 int b=0 println "a is ${a} , b is ${b}" [a,b]=f1(a) println "a is NOW ${a} , b is NOW ${b}" def f1(int x) { return [a*10,a*20] } 
+43
groovy
Jul 20 '11 at 5:50
source share
2 answers

You almost have it. Conceptually, [ a, b ] creates a list, and ( a, b ) expands one, so you want (a,b)=f1(a) instead of [a,b]=f1(a) .

 int a=10 int b=0 println "a is ${a} , b is ${b}" (a,b)=f1(a) println "a is NOW ${a} , b is NOW ${b}" def f1(int x) { return [x*10,x*20] } 

Another example returning objects that should not be of the same type:

 final Date foo final String bar (foo, bar) = baz() println foo println bar def baz() { return [ new Date(0), 'Test' ] } 

In addition, you can combine the declaration and purpose:

 final def (Date foo, String bar) = baz() println foo println bar def baz() { return [ new Date(0), 'Test' ] } 
+74
Jul 20 2018-11-11T00:
source share

You can declare and assign variables in which return values ​​are stored on one line, such as this, which is a bit more compact syntax than the one used in Justin's answer:

 def (int a, int b) = f1(22) 

In your particular case, you cannot use this because one of the variables passed to f1 is also used to store the return value

+33
Jul 20 '11 at 8:40
source share



All Articles