Groovy multiple assignment with a map

风格不统一 提交于 2020-01-03 10:18:53

问题


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


来源:https://stackoverflow.com/questions/24556816/groovy-multiple-assignment-with-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!