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.

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

We can have types as part of the declaration

def (int a,String b) = [10,'someString']

With method calls

def someMethod(){
[5,'Hello']
}
def (int a,String b) = someMethod()

For more information see Multiple Assignments.

Ankur
ankur@intelligrape.com

Tag -

FOUND THIS USEFUL? SHARE IT

comments (1 “Multiple Variable Assignment in Groovy”)

Leave a comment -