
reference.language.category_methods_setters.html Maven / Gradle / Ivy
Categories
Setters
Attribute values are normally set siply by copying the value provided when creating objects or assigning a value to an attribute.
This covers most use cases, but there are situations where you want to:
- validate the value in a way which is not supported by attribute constraints
- transform the value "on the fly" rather than just store it
- take the opportunity to populate other values
This is where setters are useful.
Setters are special methods defined as part of a category definition, and attached to a particular attribute name.
When a setter is defined and a piece of code tries to set the corresponding attribute, including when the object is created,
Prompto will call the setter to transform the value prior to setting it.
Within the setter method body, the name of the attribute being set holds the value received, which can be used for whatever purpose.
The setter is a function which MUST return the value to be written.
In the below example, we define a setter for a fullName attribute which returns a capitalized value, and sets the initials attribute:
Cyclical dependencies
Prompto manages cyclical dependencies between setters. Cyclical dependencies occur when for example setter for 'a' sets 'b' and setter for 'b' sets 'a'.
During the execution of a setter body, it is guaranteed that the setter being executed will not be called again for the current object
until the execution of the initial setter is complete.