I want to return multiple values from a function written in groovy and receive them , but i am getting an error
class org.codehaus.groovy.ast.expr.ListExpression, with its value '[a, b]', is a bad expression as the left hand side of an assignment operator
My code is
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] }
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.
Even though a function can return only one value but that value can be of pointer type.
The last line of a method in Groovy is automatically considered as the return statement. For this reason, an explicit return statement can be left out. To return a value that is not on the last line, the return statement has to be declared explicitly.
You almost have it. Conceptually [ a, b ]
creates a list, and ( a, b )
unwraps 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, which don't need to be the same type:
final Date foo final String bar (foo, bar) = baz() println foo println bar def baz() { return [ new Date(0), 'Test' ] }
Additionally you can combine the declaration and assignment:
final def (Date foo, String bar) = baz() println foo println bar def baz() { return [ new Date(0), 'Test' ] }
You can declare and assign the variables in which the return values are stored in one line like this, which is a slightly more compact syntax than that used in Justin's answer:
def (int a, int b) = f1(22)
In your particular case you may not be able to use this because one of the variables passed to f1
is also used to store a return value
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