Groovy multiple assignment with a map

2019-06-20 05:49发布

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]

2条回答
女痞
2楼-- · 2019-06-20 06:21

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()
查看更多
冷血范
3楼-- · 2019-06-20 06:32

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
查看更多
登录 后发表回答