Search code examples
oopcommon-lispclass-names

Why does `class-name` does not work in the REPL for this case?


I am reading the book Object Oriented Programming in Common Lisp from Sonja Keene.

In chapter 7, the author presents:

(class-name class-object)

This would make possible to query a class object for its name.

Using SBCL and the SLIME's REPL, I tried:

; SLIME 2.26.1
CL-USER> (defclass stack-overflow () 
           ((slot-1 :initform 1 )
            (slot-2 :initform 2)))
#<STANDARD-CLASS COMMON-LISP-USER::STACK-OVERFLOW>
CL-USER> (make-instance 'stack-overflow)
#<STACK-OVERFLOW {1002D188E3}>
CL-USER> (defvar test-one (make-instance 'stack-overflow))
TEST-ONE
CL-USER> (slot-value test-one 'slot-1)
1
CL-USER> (class-name test-one)
; Evaluation aborted on #<SB-PCL::NO-APPLICABLE-METHOD-ERROR {10032322E3}>.

The code above returns the error message below:

There is no applicable method for the generic function
  #<STANDARD-GENERIC-FUNCTION COMMON-LISP:CLASS-NAME (1)>
when called with arguments
  (#<STACK-OVERFLOW {1003037173}>).
   [Condition of type SB-PCL::NO-APPLICABLE-METHOD-ERROR]

How would be the proper use of class-name?

Thanks.


Solution

  • The argument to class-name must be a class object, not an instance of the class.

    Use class-of to get the class of the instance, then you can call class-name

    (class-name (class-of test-one))