问题
In Groovy, I have a function that returns a triple. I'd like to:
- put the first value returned in a
Mapfor an arbitrary key and - assign the two other values to variables.
I can do:
Map m = [:]
(day, month, year) = "12 February 2014".split(" ");
m["day"] = day;
But I would like to get rid of the variable day, like this:
Map m = [:]
(m["day"], month, year) = "12 February 2014".split(" ");
For some reason it seems to be not possible. This is what the compiler alerts me about:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/web/com/139223923319646/main.groovy: 2: expecting ')', found ',' @ line 2, column 10.
(m["day"], month, year) = "12 February 2014".split(" ");
^
Would you guys be able to either help me or explain to me why this syntax cannot be used?
回答1:
You can do this:
def dstr = "12 February 2014"
def m = [['day', 'month', 'year'], dstr.split( " " )].transpose()
.collectEntries()
To get
assert m == [ day:'12', month:'February', year:'2014' ]
But I'm not sure that's what you want...
回答2:
This is not possible unfortunately, according to the multiple assignment Groovy documentation.
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()
Your first example is the best way to do this currently.
来源:https://stackoverflow.com/questions/21739658/multiple-assignment-using-a-maps-value-instead-of-a-variable-with-groovy