Multiple Variable Assignment in Groovy

14 / Dec / 2010 by Ankur Tripathi 1 comments

In one of my project, I was in need to return multiple variables from a method. I searched and found very good Groovy way for ‘Multiple Assignment’, This allows us to assign multiple variables at once.

[groovy]def (str1,str2,str3) = [‘Groovy’,’and’,’Grails’]
assert str1 == ‘Groovy’ && str2 == ‘and’ && str3 == ‘Grails'[/groovy]

We can have types as part of the declaration
[groovy]
def (int a,String b) = [10,’someString’]
[/groovy]

With method calls
[groovy]
def someMethod(){
[5,’Hello’]
}
def (int a,String b) = someMethod()
[/groovy]

For more information see Multiple Assignments.

Ankur
ankur@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Multiple Variable Assignment in Groovy”)

Leave a Reply

Your email address will not be published. Required fields are marked *