How Do You Create a Class for Objects with Many Data Members and Access One Specific Data Member in Groovy?

Problem scenario
You want to use Groovy to create a class and an object that is composed of many individual member data types.  How do you do this and access an individual data type of the object?

Solution
This Groovy program creates two objects from the same class using different syntax.  One method uses syntax "[]" and another method uses the "new" keyword.

@groovy.transform.Canonical
class Program {
    String mem1 = ""
    String mem2 = ""
    String mem3 = ""
    String mem4 = ""
    String mem5 = ""
    String mem6 = ""
    String mem7 = ""
    String mem8 = ""
    String mem9 = ""
}

programsv1 = new Program( "1", "2", "3", "4", "5", "6", "7", "8", "9")
Program[] programsV2 = [[" ", "x", " ", " ", " ", " ", " ", " ", " ",]]

println programsv1.mem8
println programsV2.mem2

Leave a comment

Your email address will not be published. Required fields are marked *