匿名 CLOS 实例

发布于 2025-01-08 16:53:49 字数 321 浏览 2 评论 0原文

在 Common Lisp 中,是否有一种白话可以像 Java 中那样定义匿名类,用于一次性的“小型接口实现者”?

例如,

this.addListener(new Listener() {
    public void listen() {...}
});

如:

(defgeneric listen (object))

(add-listener #<this>
  (make-anonymous-instance
    (listen (object) ...)))

Is there a vernacular, in Common Lisp, for defining Anonymous Classes in the manner in which one might in Java, for one-off 'small interface implementors'?

For instance,

this.addListener(new Listener() {
    public void listen() {...}
});

as:

(defgeneric listen (object))

(add-listener #<this>
  (make-anonymous-instance
    (listen (object) ...)))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

滿滿的愛 2025-01-15 16:53:49

在 Common Lisp 中,方法属于泛型函数,而不是类,因此匿名实例实际上没有意义。根据具体情况,通过槽封闭或 EQL 专用器可以实现类似的目的。

扩展回应评论:

在 CL 中定义不在顶层的方法是可能的,但这并不是一个好主意。我建议只添加通常的方法,如果不需要实际实例,可能是专门针对符号或其他常量的 EQL。

如果定义内联行为通常很有用,那么它表明接口设计错误,应该采用闭包而不是对象。如果您无法修复接口本身,那么您可以定义一个类,其唯一目的是包装一个闭包并添加一个调用该闭包的方法,然后创建一个具有适当行为的实例。

In Common Lisp methods belong to generic functions, not classes, therefore anonymous instances don't really make sense. Similar purposes can be achieved, depending on specific circumstances, trough closures or EQL specializers.

Extended in response to comment:

In CL defining methods not at top-level is possible, but not really a good idea. I would suggest just adding the method normally, possibly EQL specialized on a symbol or other constant if no actual instance is needed.

If defining behaviour inline is useful more often than not then it indicates that the interface is misdesigned and should take a closure and not an object. If you cannot fix the interface itself then you could define a class which only purpose is to wrap a closure and add a method calling that closure, then just make an instance with appropriate behaviour slotted.

温柔嚣张 2025-01-15 16:53:49

并不真地。尽管有了 MOP 和一些宏观学,这可能是可能的。

在 CLOS 开发的早期阶段,有人提出了类似 GENERIC-FLET 的方案。但它没有进入标准。

NOt really. Though with the MOP and some macrology it might be possible.

In the early phase of the development of CLOS there was something like GENERIC-FLET proposed. But it did not make it into the standard.

心头的小情儿 2025-01-15 16:53:49

Java中的匿名类几乎总是用来实现匿名函数和闭包。在 Common Lisp 中,不需要模拟 Java 的匿名内部类,因为函数是 Common Lisp 中的第一类类型。

如果是这种情况,那么 Common Lisp 中的代码将如下所示:

(add-listener self (lambda (object) ...))

Anonymous classes in Java are almost always used to implement anonymous functions and closures. In common lisp, there is no need to emulate Java's anonymous inner classes since function is a first-class type in Common Lisp.

If this is the case, then the code in Common Lisp would look like:

(add-listener self (lambda (object) ...))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文