In Common Lisp, what is the correct way to define a type or nil in a class slot?

In Common Lisp, what is the correct way to define a type or nil in a class slot?

I have a class, in which I want some slots to be nil when object is created, but they should be only setable with objects of some certain type. Something like:

(defclass Something ()
  ((foo :initarg :foo :type (or character 'nil) :initform nil :accessor something-foo)))

If I say just :type character, or :type (or character nil), than SBCL complains about nil not be of asserted type of character. If I say :type (or character 'nil), than it seems like it accept character and the symbol type, since any symbol seems to go:

CL-USER> (defvar *foo* (make-instance 'Something))
*FOO*
CL-USER> (setf (something-foo *foo*) 'test)
TEST
CL-USER> (something-foo *foo*)
TEST

Is there a way to assert that a slot is either nil, or has the given type? Or should I just leave out the type specifier, and assert the type in the accessor or writer method?

Edit:

After a second thought, perhaps the idiom is to say :type characterbut leave it unbound, and than check for the slot being bound or not, instead of checking for nil and not-nil?

Answer

NIL is the empty type, it contains no values at all (like the empty set in mathematics).

The type that contains the value NIL is NULL. So what you want is

:type (or character null)

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles