10.2 Getters and setters for slots

As shown in Section 4.4, page 42, when you define a class, Dylan automatically defines a getter method to return the value of a slot, and defines a setter method to change the value of a slot.

Performance note: For slot accesses, given accurate type declarations, the compiler can typically optimize away not only the method dispatch, but also the function call, making the executed code just as efficient as it would be in a language such as C, where structure or record slots are accessed directly. See Chapter 19, Performance and Flexibility.

The name of the getter is always the name of the slot. Thus, the getter for the total-seconds slot is total-seconds. Let's look at an example of calling a getter. The first expression is an abbreviation for the second expression:

*my-time-of-day*.total-seconds;
total-seconds(*my-time-of-day*);

The preceding expressions are calls to the getter function named total-seconds. The choice of which syntax to use is purely a matter of personal style. The first syntax is provided for those people who prefer the slightly more concise dot syntax. The second syntax is provided for those people who prefer slot accesses to look like function calls. In this book, we use the dot syntax.

By default, the name of the setter is the slot's name followed by -setter. Thus, the setter for the total-seconds slot is total-seconds-setter. You can use the :setter slot option to specify a different name for the setter.

The dot-syntax abbreviation for assignment enables you to invoke the setter by using assignment with the name of the getter. For example, the first two expressions are abbreviations for the third expression:

*my-time-of-day*.total-seconds := 180;
total-seconds(*my-time-of-day*) := 180;
total-seconds-setter(180, *my-time-of-day*);

Each of these expressions stores the value 180 in the slot named total-seconds of the object that is the value of the *my-time-of-day* variable.

Most Dylan programmers do not use the syntax of the third expression to call a setter, because it is more verbose than the first and second expressions. However, it is important to know the name of the setter, so that you can define setter methods. For example, to define a method on the setter for the total-seconds slot, you define it on total-seconds-setter. For an example of a setter method, see Section 10.2.2.

If you do not want Dylan to define a setter method for a slot, you can define the slot to be constant, using the constant slot adjective, or you can give the :setter #f slot option.

For more information about accessing slots, see Section 12.1.2, page 163, and Section 12.1.6, page 166.