Lisp - Slots and Accessors



A class contains slots and accessors to manage the data associated with the object. In this chapter, we're discussing slots and accessors in details with examples.

Class Slots

A slot represents the data attribute/member of the class. A slot contains the value representing the state of the object. Slots are defined within a class using defclass form.

Class Slot Characteristics

  • name − Each slot has a name.

  • :initform − We can initialize the slot with a value using :initform option.

  • :initarg − We can initialize slot with other object using:initarg option.

  • :type − :type is used to define the type of the slot

Example - Class Slots

main.lisp

; define a class
(defclass box ()
   ((length :initform 1 :accessor box-length :type integer)
   (breadth :initform 1 :accessor box-breadth :type integer)
   (height :initform 1 :accessor box-height :type integer)))
   
; create an instance of class box and assign to an item
(setf item (make-instance 'box))

; print length of the box
(format t "Length of the Box is ~d~%" (box-length item))
; print breadth of the box
(format t "Breadth of the Box is ~d~%" (box-breadth item))
; print height of the box
(format t "Height of the Box is ~d~%" (box-height item))

Output

When you execute the code, it returns the following result −

Length of the Box is 1
Breadth of the Box is 1
Height of the Box is 1

In this example, length, breadth and height are slots of box class.

Class Accessors

A class accessor is a function to get and set value of a slot. CLOS automatically generates accessor functions when an :accessor, :reader a and :writer options are used within defclass.

Types of Class Accessor

  • :accessor − it signities to create both get and set method.

  • :reader − it signfiies to create only get method.

  • :writer − it signifies to create only set method.

Example - Class Accessors

main.lisp

; define a class
(defclass box ()
   ((length :initform 1 :accessor box-length :type integer)
   (breadth :initform 1 :accessor box-breadth :type integer)
   (height :initform 1 :accessor box-height :type integer)))
   
; create an instance of class box and assign to an item
(setf item (make-instance 'box))

; get length of the box using getter method
(format t "Length of the Box is ~d~%" (box-length item))

; update length of the box using setter method
(setf (box-length item) 20)

; get updated length of the box using getter method
(format t "Updated length of the Box is ~d~%" (box-length item))

Output

When you execute the code, it returns the following result −

Length of the Box is 1
Updated length of the Box is 20
Advertisements