Clojure reify a Java interface with overloaded methods

核能气质少年 提交于 2019-12-07 04:37:35

问题


I'm trying to implement the following Java interface in Clojure:

package quickfix;

public interface MessageFactory {
    Message create(String beginString, String msgType);
    Group create(String beginString, String msgType, int correspondingFieldID);
}

The following Clojure code is my attempt at doing this:

(defn -create-message-factory 
  []
  (reify quickfix.MessageFactory
    (create [beginString msgType]
      nil)
    (create [beginString msgType correspondingFieldID]
      nil)))

This fails to compile with the error:

java.lang.IllegalArgumentException: Can't define method not in interfaces: create

The documentation suggests overloaded interface methods are ok, so long as the arity is different as it is in this case:

If a method is overloaded in a protocol/interface, multiple independent method definitions must be supplied. If overloaded with same arity in an interface you must specify complete hints to disambiguate - a missing hint implies Object.

How can I get this working?


回答1:


You're missing a parameter. The first parameter of every method implemented by reify is the object itself (as is the case with defrecord/deftype). So, try this:

(defn -create-message-factory 
  []
  (reify quickfix.MessageFactory
    (create [this beginString msgType]
      nil)
    (create [this beginString msgType correspondingFieldID]
      nil)))


来源:https://stackoverflow.com/questions/21000267/clojure-reify-a-java-interface-with-overloaded-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!