Multiple Assignment

Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.:

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.:

def (int i, String j) = [10, 'foo']

As well as used when declaring variables (as above) it also applies to existing variables, e.g.:

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.:

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.:

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.:

def (a, b) = [1, 2, 3]
assert a == 1 && b == 2

Notes: