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

Time:10-01

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.

CodePudding user response:

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))

CodePudding user response:

Using @Barmar's hint on a comment, this would the correct approach with class-name:

CL-USER> (class-name (defclass stack-overflow () 
                       ((slot-1 :initform 1 )
                        (slot-2 :initform 2))))
STACK-OVERFLOW

class-name receives as an argument a class. In order to work with instances, the correct approach is using class-of:

CL-USER> (class-of 'test-one)
#<BUILT-IN-CLASS COMMON-LISP:SYMBOL>

I am not sure why class-name would be helpful, though.

  • Related