Skip to main content

no-applicable-method

no-applicable-method Standard Generic Function

Syntax:

no-applicable-method generic-function &rest function-arguments → {result}*

Method Signatures:

no-applicable-method (generic-function t)

&rest function-arguments

Arguments and Values:

generic-function—a generic function on which no applicable method was found.

function-argumentsarguments to the generic-function.

result—an object.

Description:

The generic function no-applicable-method is called when a generic function is invoked and no method on that generic function is applicable. The default method signals an error.

The generic function no-applicable-method is not intended to be called by programmers. Programmers may write methods for it.

Exceptional Situations:

The default method signals an error of type error.

See Also:

Expanded Reference: no-applicable-method

Default Behavior

When a generic function is called and no methods are applicable, no-applicable-method is invoked. The default method signals an error.

(defgeneric process-item (item))

;; Only a method for strings
(defmethod process-item ((item string))
(string-upcase item))

;; Calling with an integer has no applicable method:
(handler-case (process-item 42)
(error () :caught-error))
=> :CAUGHT-ERROR

Defining a Custom no-applicable-method Handler

You can define a method on no-applicable-method to provide a fallback or custom behavior instead of signaling an error.

(defgeneric safe-lookup (key))

(defmethod safe-lookup ((key symbol))
(format nil "Found symbol: ~A" key))

(defmethod no-applicable-method ((gf (eql #'safe-lookup)) &rest args)
(format nil "No handler for ~A" (first args)))

(safe-lookup :hello)
=> "Found symbol: HELLO"

(safe-lookup 42)
=> "No handler for 42"

Providing Default Return Values

A custom no-applicable-method can return a sensible default instead of failing.

(defgeneric convert-to-string (obj))

(defmethod convert-to-string ((obj number))
(format nil "~A" obj))

(defmethod no-applicable-method ((gf (eql #'convert-to-string)) &rest args)
(format nil "~S" (first args)))

(convert-to-string 42)
=> "42"
(convert-to-string '(1 2 3))
=> "(1 2 3)"