Multiple Assignment
Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.:
| Code Block |
|---|
def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo' |
You can provide types as part of the declaration if you wish, e.g.:
| Code Block |
|---|
def (int i, String j) = [10, 'foo'] |
As well as used when declaring variables (as above) it also applies to existing variables, e.g.:
| Code Block |
|---|
def nums = [1, 3, 5] def a, b, c (a, b, c) = nums assert a == 1 && b == 3 && c == 5 |
The syntax works for arrays as well as lists, as well as methods that return either of these, e.g.:
| Code Block |
|---|
def (_, month, year) = "18th June 2009".split() println "In $month of $year" // => In June of 2009 |
Overflow and Underflow
If the left hand side has too many variables, excess ones are filled with null's, e.g.:
| Code Block |
|---|
def (a, b, c) = [1, 2] assert a == 1 && b == 2 && c == null |
If the right hand side has too many variables, the extra ones are ignored, e.g.:
| Code Block |
|---|
def (a, b) = [1, 2, 3] assert a == 1 && b == 2 |
Notes:
- currently only simple variables may be the target of multiple assignment expressions, e.g. if you have a
personclass withfirstnameandlastnamefields, you can't currently do this:Code Block (p.firstname, p.lastname) = "My name".split()
- currently multiple assignment cannot be used for declaring multiple class fields and initializing them as:
Code Block class Foo { def (i,j) = [1,2] }