1

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
  • 1
    See the bottom of this page groovy.codehaus.org/Multiple+Assignment - they don't exactly say why, other than only use with 'simple variables, which means you map is not a 'simple' object. Someone more Groovy-savvy, (like maybe Tim Yates!) might be able to fill in the blanks. Commented Feb 12, 2014 at 21:52

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Oops, it seems that I just couldn't find that information myself! Sorry about that, and thank you for your reply ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.