Good day. Began to study Groovy and the following problem arose.

There is a code for storing meta data:

class Meta { final MetaItem name final MetaItem description // ... // Еще куча полей с типом MetaItem // ... Meta() { name = new MetaItem("name") description = new MetaItem("description") } void setName(String name) { this.name.value = name } String getName() { return this.name.value } void setDescription(String description) { this.description.value = description } String getDescription() { return this.description.value } // ... // Еще куча методов. По два на каждое поле // ... } class MetaItem { private final def id def value MetaItem(String id) { this.id = id } } // Проверка def meta = new Meta() assert meta.name == null assert meta.description == null meta.with { name = "Name" description = "Desc" } assert meta.name == "Name" assert meta.description == "Desc" print "Success!" 

As can be seen from the code, it greatly increases in volume when adding new fields, since two methods should be added to each field. Is it possible to somehow optimize it? Somehow to redirect the assignment. I looked in the direction of Delegate, but I realized that this was not the case.

PS The variant with adding .value , unfortunately does not suit me, because all this is in the extension of the plug for Gradle

    1 answer 1

    The easiest way is to implement an AST transformation, which will generate all these getName() setName() when a field of the MetaItem type with the name name detected.