Annotation Type AutoFinal
The annotation can be placed at the class level in which case it applies to all methods, constructors, and closures within the class and any inner classes. It can also be applied to an individual method, constructor, field with a Closure initial value or a Closure assigned to a local variable. In the case of fields (or local variables) it only adjusts the parameters of the referenced Closure not the field (or local variable) itself.
If you wish to automatically apply the
annotation to all classes of a project, consider using
groovyc --configscript
. Google "Customising The Groovy Compiler",
or see CompilerConfiguration
for further details.
This will ensure that all arguments will automatically be final,
completely eliminating the need to clutter the code with final keywords
in any parameter list.
Example usage:
for this case, the constructor for the@groovy.transform.AutoFinal
class Person { final String first, last Person(String first, String last) { this.first = first this.last = last } String fullName(boolean reversed = false, String separator = ' ') { final concatCls = { String n0, String n1->
"$n0$separator$n1" } concatCls(reversed ? last : first, reversed ? first : last) } } final js = new Person('John', 'Smith') assert js.fullName() == 'John Smith' assert js.fullName(true, ', ') == 'Smith, John'
Person
class will be
equivalent to the following code:
Person(final String first, final String last) { ... }And after normal default parameter processing takes place, the following overloaded methods will exist:
String fullName(final boolean reversed, final String separator) { ... } String fullName(final boolean reversed) { fullName(reversed, ' ') } String fullName() { fullName(false) }and the closure will have become:
{ final String n0, final String n1 ->
"$n0$separator$n1" }
- Since:
- 2.5.0
-
Optional Element Summary
Modifier and TypeOptional ElementDescriptionboolean
Indicates that adding final to parameters should not be applied on this node.
-
Element Details
-
enabled
boolean enabledIndicates that adding final to parameters should not be applied on this node.Normally not required since leaving off the annotation will achieve the same effect. However, it can be useful for selectively disabling this annotation in just a small part of an otherwise annotated class. As an example, it would make sense to set this to
false
on a method which altered parameters in a class already marked as@AutoFinal
. All nodes in the class except that single method would be processed.- Default:
- true
-