使用地图进行Groovy多重赋值

时间:2014-07-03 14:43:17

标签: groovy variable-assignment

我在为地图中的值执行多重赋值语句时遇到问题。

def map = [a:1,b:2]
(map.a, map.b) = [3,4]

这引发了一个例外:

expecting ')', found ',' at line: 2, column: 7

然而,这很好用:

def a = 1
def b = 2
(a, b) = [3,4]

2 个答案:

答案 0 :(得分:8)

实际上,如果你作弊并使用.with

,你可以这样做
Map map = [a: 1, b:2]

map.with {
    (a, b) = [3, 4]
}

assert map.a == 3
assert map.b == 4

答案 1 :(得分:4)

它不支持。

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