Groovy multiple assignment with a map

2019-06-20 06:03发布

问题:

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]

回答1:

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


回答2:

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()