This page looks at proposed changes to the Groovy language to support multiple assignment. Such support would allow for code such as:
It is meant to be a discussion document, not a formal definition, we will work out the impact on the grammar etc. once we clarify our intention.
Some existing declarations involving single assigment:
In order to not conflict with existing definitions, any variable declaration which wishes to make use of multiple assignments must surround the 'tuple' of variable declarations in round brackets. Whenever such a round bracket is found, the compiler will match the tuple with a list. The list will be expected to be where it would be in the case of single assignment. The compiler will 'unpack' the list into the tuple of variables.
Nested variations are also supported (this may be deferred initially):
Differing sized tuples and lists are catered for by ignoring extra list members and leaving any untargeted variables in the tuple set to null:
There can be at most one [at the end like varargs?] 'tuple spread' operator which takes the rest of the list:
Setting a bunch of variables to the same (or related) values is accomplished using normal list conventions:
The tuple list is strictly a list (apart from the nesting seen earlier) and may not contain assignments itself:
Example involving nulls:
Examples involving real world use:
Use in Expressions
The left hand side (LHS) of an expression involving the simple assignment operator,
=, can be replaced with a tuple. In this case, the variables will be predefined or binding variables and the result of the RHS of the expression will be a (possibly coerced) list which will be unpacked into the tuple.
Where it is not ambiguous, the round brackets can be removed from the tuple list when used in such expressions, so the above could be written as:
If the right hand side after any assignment operator contains a comma separated list of subexpressions, they will be assumed to make up a list (i.e. automatically turned into a list), so the above could be written as:
[Note: the above probably requires lots of pouring over the grammar!]
If you find you need a tuple with different typed items inside, use an expression form rather than the variable declaration form which requires the types to be the same, e.g.:
Unlike with declarations, the LHS doesn't need to simply be a variable:
Other examples which need to work:
Other assignment operators
These may not be implemented initially, but we attempt to define them here. It includes these:
First, a tuple on the LHS of a special assignment operator:
Now, an example with special treatment on the RHS:
As an alternative to the semantics described here, we could define '
a, b *= 3' to be the same as '
a *= 3; b *= 3'. This seems more useful but then if the semantics were to be consistent, then '
a, b = 3' should mean '
a = 3; b = 3'.
Use in Method declarations
No change, no grouping of method parameters is supported, i.e. the following is invalid: