Structs in Groovy

Our example demonstrates working with structs, which are typed collections of fields that can be used to group data together to form records.

// This example demonstrates the use of classes and properties in Groovy.

class Person {
    String name
    int age

    Person(String name) {
        this.name = name
        this.age = 42
    }
}

def newPerson(String name) {
    return new Person(name)
}

def main() {
    // Creating a new instance of the Person class
    println new Person("Bob", 20)

    // Initializing a class with named parameters
    def alice = new Person(name: "Alice", age: 30)
    println alice

    // Fields that are not set will have default value
    def fred = new Person(name: "Fred")
    println fred

    // Using the newPerson function to create a new instance
    println newPerson("Jon")

    // Accessing class field
    def sean = new Person(name: "Sean", age: 50)
    println sean.name

    // Groovy automatically dereferences pointers
    def sp = sean
    println sp.age

    // Modifying a class property
    sp.age = 51
    println sp.age

    // Anonymous classes
    def dog = [name: "Rex", isGood: true]
    println dog
}

main()

In this example, we’ve created a Person class with name and age fields. We also defined a constructor that initializes the name and sets the age to 42 by default. The newPerson function is used for creating a new Person instance.

To run the program, save the code in a .groovy file and use the groovy command to execute it.

$ groovy Example.groovy
Person(Bob, 20)
Person(name:Alice, age:30)
Person(name:Fred, age:42)
Person(name:Jon, age:42)
Sean
50
51
[name:Rex, isGood:true]

Now that we can run and build basic Groovy programs with classes, let’s learn more about the language.