Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy multiple assignment with a map

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]
like image 989
David Sawyer Avatar asked Jul 03 '14 14:07

David Sawyer


People also ask

How do I assign multiple values to a variable in Groovy?

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.

How do I add a map to Groovy?

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.

What is multi assignment?

multiple assignment A form of assignment statement in which the same value is given to two or more variables.

Can you do multiple assignments in Java?

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.


2 Answers

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
like image 179
Igor Avatar answered Sep 18 '22 17:09

Igor


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()
like image 22
evanwong Avatar answered Sep 17 '22 17:09

evanwong