Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy initialization of array of objects

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?

like image 799
Captain Franz Avatar asked Feb 25 '14 03:02

Captain Franz


1 Answers

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

like image 89
dmahapatro Avatar answered Sep 30 '22 02:09

dmahapatro