I am having a problem doing a multiple assignment statement for values in a map.
def map = [a:1,b:2]
(map.a, map.b) = [3,4]
this throws an exception:
expecting ')', found ',' at line: 2, column: 7
However, this works fine:
def a = 1
def b = 2
(a, b) = [3,4]
Since Groovy 1.6 we can define and assign values to several variables at once. This is especially useful when a method returns multiple values and we want to assign them to separate variables. // Assign and declare variables. // We can assign later than the definition of the variables.
Add Item to a Map The first way is using the square brackets for the key. This way useful if you have a dynamic key name for example the key name join with index. The second way is using a key separate with map name by a dot ".". Or this example also working in Groovy.
multiple assignment A form of assignment statement in which the same value is given to two or more variables.
Java permits the use of multiple assignments in one statement. In such statements, the assignment operators are applied from right to left, rather than from left to right.
Actually, you can do this if you cheat and use .with
:
Map map = [a: 1, b:2]
map.with {
(a, b) = [3, 4]
}
assert map.a == 3
assert map.b == 4
It doesn't support that.
http://groovy.codehaus.org/Multiple+Assignment
currently only simple variables may be the target of multiple assignment expressions, e.g.if you have a person class with firstname and lastname fields, you can't currently do this:
(p.firstname, p.lastname) = "My name".split()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With