Groovy Record: Simplified Syntax and Immutable Characteristics

Starting from Groovy 3.0, a new language feature known as Record Classes has been introduced. A record class is a type of data representation that resembles Java's POJOs (Plain Old Java Objects) but offers significantly more concise and convenient syntax.

Here is an example of defining and using Record Classes in Groovy:

record Person(String name, int age) {
    void sayHello() {
        println("Hello, my name is ${name}, and I'm ${age} years old.")
    }
}

def person = new Person("Alice", 25)
println(person.name) // Outputs "Alice"
println(person.age) // Outputs 25
person.sayHello() // Outputs "Hello, my name is Alice, and I'm 25 years old."

In the example above, we define a Person record class with two properties: name and age, along with a method named sayHello. When defining the record class, we utilize concise syntax to declare both the properties and constructor parameters simultaneously. Subsequently, we instantiate a Person object and access its properties and methods directly.

It is important to note that record classes are immutable. Once an instance of a record class is created, its property values cannot be modified. If modification of a specific property value is required, a new object must be instantiated instead. Furthermore, record classes support automatic implementation of equals, hashCode, and toString methods, making them more convenient to use out-of-the-box.

In Groovy, you can also utilize annotations such as @ToString, @EqualsAndHashCode, and @TupleConstructor to customize the behavior of a record class. Additionally, records support using with and copy methods for creating modified copies or accessing properties in specific contexts (though note that standard immutable semantics still apply unless explicitly overridden via these utility patterns).