Groovy初始化对象数组

时间:2014-02-25 03:12:22

标签: arrays object groovy initialization

我正在寻找最简洁的语法来初始化Groovy中的对象数组。 给出:

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

我目前正在这样做:

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[]

我似乎记得在Java中有一种更紧凑的语法,可能不需要使用new关键字。什么是最紧凑的Groovy语法来实现这一目标?

1 个答案:

答案 0 :(得分:18)

@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

请回答@ Igor的问题。