MyArchiBook

@Canonical = @ToString + @TupleConstructor + @EqualsAndHashCode

with 3 comments

ToString in Groovy:

In Java , we override toString() to print results.

In Groovy, this can be achieved simply, by using the @ToString annotation which is one of the A.S.T Transformation traits.(Example given below)

Tuple Constructor:

import groovy.transform.ToString

@ToString
class Car{
  Long carID
  String carBrand
  String carModelNo
}

Car car=new Car(carID:10,carBrand:"Audi",carModelNo:"Q5")
println car                                      // O/P: Car(10, Audi, Q5)
car.carID=1
println car                                      // O/P: Car(1, Audi, Q5)
car.setCarID(4)
println car                                      // O/P: Car(4, Audi, Q5)

In a POGO class, the values to the atributes can be set in the above following ways,

  • Using a default constructor, where the attribute and its value is set as Key-Value pairs.
  • By creating a reference for the class and just denoting ref.attributeName=value
  • Setting values using Setter method.

However, values can also be set using Tuple Constructor like the example below,

import groovy.transform.ToString
import groovy.transform.TupleConstructor

@ToString
@TupleConstructor
class Car{
  Long carID
  String carBrand
  String carModelNo
}

Car car=new Car(15,"BENZ","E-63")
println car                       //O/P:Car(15, BENZ, E-63)

Here , the attribute key is not required. Only values are set directly.

NOTE: Values have to be set only in the order of the attributes listed in the POGO because this Tuple Constructor is a specific positional type Constructor.

The above 2 functionalities i.e., pretty print using toString() and assigning values using Tuple Constructor, along with Equals and HashCode check can be achieved by using a single annotation @Canonical which is imported from groovy.transform.Canonical

Therefore,

       @Canonical =  @ToString + @TupleCOnstructor + @EqualandHashCode

Have a great day 🙂

Advertisements

Written by thangaveluaishwarya

October 19, 2013 at 12:22 PM

3 Responses

Subscribe to comments with RSS.

  1. crisp and clear
    all topics chosen by you is nothing short of marvellous
    you take these small things and your examples are easy to understand

    Manivannan

    October 19, 2013 at 9:34 PM

  2. gud job. thanks for promoting groovy. youre in the mailing list?

    mkeeva

    November 18, 2013 at 7:09 PM

  3. Beautifully explained article.

    Dilshan

    August 21, 2015 at 7:37 PM


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: