简体   繁体   中英

ArityException occurs when clojure gen-class an interface with overloaded methods

I have an java interface as below:

public interface Wrapper {
  void error( Exception e);
  void error( String str);
}

And i am trying to create an implementation in clojure with gen-class:

(ns myimpl)

(gen-class
 :name myimpl
 :implements [Wrapper]
 :state state
 :init init
 :prefix "w-"
 :main false
 )


(defn- w-error [this ^Exception e]
  (println e))

(defn- w-error [this ^String s]
  (println s))

Then i try to create an instance and call the method in repl:

> (def w (myimpl. ))
> (.error w "oops")

This will give me an ArityException: Wrong number of args (2) passed to: myimpl$w-error.

What have i done wrong here?

The following code happens to be a misconception of how Clojure functions work.

(defn- w-error [this ^Exception e]
  (println e))

(defn- w-error [this ^String s]
  (println s))

"Regular" functions defined with defn can't dispatch on type - only on the number of arguments.

I belive that would actually be an useful and feasible feature, but we have to settle instead for multimethods and protocol implementations which together cover the 80% case for type-dispatch needs.

I don't know why are you getting an arity exception in particular, but I'd say it doesn't matter a lot.

Lastly, you might be interested in implementing your Java interface in Java, delegating the actual functionality to Clojure code. That would require either AOT-compiling your Clojure project, or dynamically loading code via RT , Var , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM