How to Make Classes Immutable in Groovy

From time to time you might have sensitive data stored in an object that you don't want modified. For example, you might assign a credit limit to a customer that should be treated as a read-only property. To ensure that object data cannot be changed you can mark a class as immutable using the @Immutable annotation.

To learn how to make a class immutable in Groovy follow these three steps:

  1. Open your text editor and type in the following lines of Groovy code:
    import groovy.transform.*
    @Immutable class Customer {
    	String name
    	String emailAddress
    	int creditLimit
    	public String toString() {
    		"Name: $name Email: $emailAddress Credit Limit: $creditLimit"
    def customer = new Customer(name: "Joe New Customer", emailAddress: "", creditLimit: 500)
    println("New customer: ${customer}")
    // The following statement will cause an exception at runtime:
    The script defines the Customer class as immutable using the @Immutable annotation. Note the import statement that specifies the package in which the annotation is located. A sample customer is created with a credit limit of $500. An attempt is made to alter the credit limit. At runtime, this will cause a ReadOnlyPropertyException.
  2. Save your file as ImmutableClass.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run Immutable Class script
    The output displays the customer object. Next, the ReadOnlyPropertyException is raised because an attempt was made to alter the credit limit.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.