Message-ID: <1933980823.141.1425538358480.JavaMail.firstname.lastname@example.org> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_140_1677393456.1425538358480" ------=_Part_140_1677393456.1425538358480 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: file:///C:/exported.html
Immutable objects are ones which don't change after initial creation. Su= ch objects are frequently desirable because they are simple and can be safe= ly shared even in multi-threading contexts. This makes them great for funct= ional and concurrent scenarios. The rules for creating such objects are wel= l-known:=20
Writing classes that follow these rules is not hard but does involve a f= air bit of boiler plate code and is prone to error. Here is what such a cla= ss might look like in Java:=20 =20
Groovy makes it easier to create such classes using the @Immutable annot= ation. You only need this:=20 =20
The "other code" shown above is added at compile time. All of = the methods you see above will be there (and you can use them from Java of = course). You just don't need to develop and maintain them.=20
A class created using @Immutable has the following characteristics:= =20
toString= code> methods are provided based on the property values.
Cloneableobjects and arrays ar= e defensively copied on the way in (constructor) and out (getters).
clonemethod. For you= r own classes, it is up to you to define this method and use deep cloning i= f appropriate.
Mapobjects are wrappe= d by immutable wrapper classes (but not deeply cloned!).
@Immutableclasses are allo= wed but for an otherwise possible mutable property type, an error is thrown= .
hashCodeme= thods. Use at your own risk!