gpt4 book ai didi

java - 用 Java 编写的类是否可以实现用 Clojure 编写的协议(protocol)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:02 25 4
gpt4 key购买 nike

我只能找到关于逆的东西;使用 Clojure 实现 Java 接口(interface)。但是,我想用 Clojure 编写一个程序并允许使用 Java 对其进行扩展。例如:

# P.clj
(defprotocol P
(f [a])
(g [a b]))

# I.java
public class I implements P {
public Object f(Object a) { … }
public Object g(Object a, Object b) { … }
}

此外,我该如何指定参数类型,这样我就不必在任何地方都使用 Object

我目前看到的唯一选择是使用点符号并依赖鸭子类型,但我更喜欢在 Java 端对接口(interface)实现进行编译时验证。

最佳答案

是的,很有可能,而且就是这样。

来自docs的相关部分:

defprotocol will automatically generate a corresponding interface, with the same name as the protocol, i.e. given a protocol my.ns/Protocol, an interface my.ns.Protocol. The interface will have methods corresponding to the protocol functions, and the protocol will automatically work with instances of the interface.

然后,回答您的问题:

A Java client looking to participate in the protocol can do so most efficiently by implementing the protocol-generated interface.

关于java - 用 Java 编写的类是否可以实现用 Clojure 编写的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21145452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com