【问题标题】:How do I implement this generic Java interface with a Clojure record?如何使用 Clojure 记录实现这个通用 Java 接口?
【发布时间】:2014-09-11 08:54:52
【问题描述】:

我正在尝试实现org.joda.time.ReadableInstant。它继承自通用接口,但显然这无关紧要。 The interface 是:

public interface ReadableInstant extends Comparable<ReadableInstant> {
    long getMillis();
    Chronology getChronology();
    DateTimeZone getZone();
    int get(DateTimeFieldType type);
    boolean isSupported(DateTimeFieldType field);
    Instant toInstant();
    boolean isEqual(ReadableInstant instant);
    boolean isAfter(ReadableInstant instant);
    boolean isBefore(ReadableInstant instant);
    boolean equals(Object readableInstant);
    int hashCode();
    String toString();
}

我的记录:

(defrecord WeirdDate [year month day]
    ReadableInstant
    (^boolean equals  [this ^Object readableInstant] (.equals (as-date this) readableInstant))
    (^int get [this ^DateTimeFieldType type] (get (as-date this) type))
    (^Chronology getChronology [this] (.getChronology (as-date this)))
    (^long getMillis [this] (.getMillis (as-date this)))
    (^DateTimeZone getZone [this] (.getZone (as-date this)))
    (^int hashCode [this] (.hashCode (as-date this)))
    (^boolean isAfter [this ^ReadableInstant instant] (.isAfter (as-date this) instant))
    (^boolean isBefore [this ^ReadableInstant instant] (.isBefore (as-date this) instant))
    (^boolean isEqual [this ^ReadableInstant instant] (.isEqual (as-date this) instant))
    (^boolean isSupported [this ^DateTimeFieldType field] (.isSupported (as-date this) field))
    (^Instant.toInstant [this] (.toInstant (as-date this)))
    (^String toString [this] (.toString (as-date this))))

但我得到了错误:

java.lang.IllegalArgumentException: Must hint overloaded method: get

我的类型提示错了吗?还有什么问题吗?

(向Clojure mailing list where I've already asked a longer version of this question 上的各位致歉,我认为这里的问题更短一些可能更容易回答)

【问题讨论】:

    标签: clojure jvm-languages clojure-java-interop


    【解决方案1】:

    您不能使用 defrecord 来实现具有 get 方法的类型,因为 get 已经在 java.util.Map 上定义,defrecord 会自动为您实现。如果你想实现这个接口,你将不得不放弃 mappiness 的细节,而只使用一个普通的 deftype。此外,您的代码中的每个类型提示都是完全不必要的:编译器知道您正在实现的接口的类型,并且不需要您的帮助来弄清楚它们。

    【讨论】:

    • 重新输入注释,我很怀疑,只是消息似乎在说“添加更多注释!”。
    • 非常感谢您的回答,就是这样。我遇到了另一个问题,也许你能抽出一点时间? stackoverflow.com/questions/25786493/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2012-11-12
    • 2017-10-23
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多