Multiple assignment using a Map's value instead of a variable with Groovy

独自空忆成欢 提交于 2020-01-05 08:38:23

问题


In Groovy, I have a function that returns a triple. I'd like to:

  • put the first value returned in a Map for 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

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