10.6 Virtual slots
Virtual slots are useful when there is information conceptually associated with an object that is better computed than stored in an ordinary slot. By using a virtual slot instead of writing a method, you make the information appear like a slot to the callers of the getter. The information appears like a slot because the caller cannot distinguish the getter of a virtual slot from a getter of an ordinary slot. In both cases, the getter takes a single required argument — the instance — and returns a single value.
A virtual slot does not occupy storage; instead, its value is computed. When you define a virtual slot, Dylan defines a generic function for the getter and setter. You must define a getter method to return the value of the virtual slot. Unlike those of other slots, the value of a virtual slot can change without a setter being called, because that value is computed, rather than stored. You can optionally define a setter method. If you want to initialize a virtual slot when you create an instance, you can define an initialize method.
We can use virtual slots to control the access to a slot. For example, we want to ensure that the value of the direction slot is north or south for <latitude>, and is east or west for <longitude>. (An alternative technique is to use enumeration types, as shown in Section 19.5, page 318.) To enforce this restriction, we must
Check the value when the setter method is invoked. In this section, we show how to do this check using a virtual slot. We also show how to use symbols, instead of strings, to represent north, south, east, and west.
Check the value of the
directionslot when an instance is created and initialized. We do that checking in Section 10.6.3.
We redefine the <directed-angle> class to include a virtual slot and an ordinary slot:
define abstract class <directed-angle> (<angle>) virtual slot direction :: <symbol>; slot internal-direction :: <symbol>; end class <directed-angle>;
We define the slot direction with the virtual slot allocation. Notice that the slot's allocation appears before the name of the slot (as contrasted with slot options, which appear after the name of the slot).
In the <directed-angle> class, we use the slot internal-direction to store the direction. We shall provide a setter method for the virtual slot direction that checks the validity of the value of the direction before storing the value in the internal-direction slot.




