使用Map的值而不是Groovy的变量进行多次赋值 [英] Multiple assignment using a Map's value instead of a variable with Groovy

查看:368
本文介绍了使用Map的值而不是Groovy的变量进行多次赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy 中,我有一个返回三元组的函数。
我希望:


  • 放入<$ c $返回的第一个值c> Map 为任意键和
  • 将其他两个值赋值给变量。


我可以这样做:

  Map m = [:] 
(日,月,年)=2014年2月12日.split();
m [day] = day;

但是我想摆脱变量 day ,像这样:

  Map m = [:] 
(m [day],month ,year)=2014年2月12日.split();






出于某种原因,它似乎是不可能的。这是编译器提醒我的:

  org.codehaus.groovy.control.MultipleCompilationErrorsException:启动失败:
/web/com/139223923319646/main.groovy:2:期待')',找到','@第2行,第10列。
(m [day],month,year)=2014年2月12日。分裂( );
^

你们能帮我解释一下为什么这个语法无法使用?

解决方案

您可以这样做:

  def dstr =2014年2月12日
def m = [''''','month','year'],dstr.split()]。
.collectEntries()

获得

  assert m == [day:'12',month:'February',year:'2014'] 

但我不确定那就是你想要的...


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?

解决方案

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...

这篇关于使用Map的值而不是Groovy的变量进行多次赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆