Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to accept multiple parameters from returning function in groovy

Tags:

groovy

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] } 
like image 513
Nikhil Sharma Avatar asked Jul 20 '11 05:07

Nikhil Sharma


People also ask

Can multiple values be returned from a function?

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.

How many parameters can be returned by a function?

Even though a function can return only one value but that value can be of pointer type.

How do I return a value in Groovy?

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.


2 Answers

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' ] } 
like image 139
Justin Piper Avatar answered Oct 09 '22 23:10

Justin Piper


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

like image 40
Dónal Avatar answered Oct 09 '22 22:10

Dónal