Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1673
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

15条回答
  •  情书的邮戳
    2020-12-08 08:58

    In Common Lisp, no-applicable-method may be used for this purpose, according to the Common Lisp Hyper Spec:

    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.

    So for example:

    (defmethod no-applicable-method (gf &rest args)
      ;(error "No applicable method for args:~% ~s~% to ~s" args gf)
      (%error (make-condition 'no-applicable-method :generic-function gf :arguments args) '()
            ;; Go past the anonymous frame to the frame for the caller of the generic function
            (parent-frame (%get-frame-ptr))))
    

提交回复
热议问题