26

I am looking for the most compact syntax to initialize an array of objects in Groovy. Given:

class Program {
    String id = ""
    String title = ""
    String genre = ""   
}

I am currently doing this:

Program[] programs = [
    new Program([id:"prog1", title:"CSI", genre:"Drama"]),
    new Program([id:"prog2", title:"NCIS", genre:"Drama"]),
    new Program([id:"prog3", title:"Criminal Minds", genre:"Crime drama"]), 
] as Program[]

I seem to recall that in Java there is a more compact syntax, possibly not requiring to use the new keyword. What is the most compact Groovy syntax to accomplish this?

2
  • 3
    could you show example of this more compact syntax from Java? Commented Feb 25, 2014 at 3:25
  • Ok, memory failed me. It's been a while since I last wrote Java code. The shortened version is indeed only for basic types, not for objects. The shortest I could write in Java does not need to mention the name of the parameters in the call to the constructor, however it still needs the new keyword. I have edited my original post accordingly. Commented Feb 25, 2014 at 15:47

2 Answers 2

31
@groovy.transform.Canonical
class Program {
    String id = ""
    String title = ""
    String genre = ""   
}

Program[] programs = [
    ["prog1", "CSI", "Drama"],
    ["prog2", "NCIS", "Drama"],
    ["prog3", "Criminal Minds", "Crime drama"]
]

println programs

Please also answer @Igor's question.

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

3 Comments

Or you can change def programs to Program[] programs and get rid of the as Program[] at the end :-)
Yup, makes more sense and less code. Changing right away. Thanks.
Thank you. This worked great. I also answered Igor's question and edited my original post accordingly.
0

The classic Java way works in groovy

int[] hi = new int[] { 3, 4, 5 }

Comments

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.