Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The @Immutable Annotation

Immutable objects are ones which don't change after initial creation. Such objects are frequently desirable because they are simple and can be safely shared even in multi-threading contexts. This makes them great for functional and concurrent scenarios. The rules for creating such objects are well-known:

  • No mutators (methods that modify internal state)
  • Class must be final
  • Fields must be private and final
  • Defensive copying of mutable components
  • equals, hashCode and toString implemented in terms of private fields

Writing classes that follow these rules is not hard but does involve a fair bit of boiler plate code and is prone to error. Here is what such a class might look like in Java:

Groovy makes it easier to create such classes using the @Immutable annotation. You only need this:

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.

  • No labels