如何使用Clojure记录实现此通用Java接口?

时间:2014-09-11 08:54:52

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

我正在尝试实施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上的那些人道歉,我认为这里更短的问题可能更容易回答)

1 个答案:

答案 0 :(得分:2)

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