1
votes

I would like to define a java interface, in clojure - (as well as implement it) - I understand implementing can be done via both proxy and gen-class, but that always assumed the interface was already defined.

2

2 Answers

5
votes

You can generate a Java interface with both clojure.core/definterface and clojure.core/gen-interface. (definterface expands to a call to gen-interface.)

(ns demo.api)

(definterface Store
  (^demo.api.Store buy [])
  (^demo.api.Store buy [^int q])
  (^demo.api.Store sell [])
  (^int getQty []))

;; or

(gen-interface
 :name demo.api.Store
 :methods [[buy [] demo.api.Store]
           [buy [int] demo.api.Store]
           [sell [] demo.api.Store]
           [getQty [] int]])

Sampled from this blog post.

If you want an "Interface", in the generic sense, then take a look at Clojure Protocols.

0
votes

Yes you can, with definterface:

 (definterface MyInterface
  (^int method1 [x])
  (^Bar method2 [^Baz b ^Quux q]))

Unlike in some of the examples of the link above though, you can now type hint ^ints, ^doubles etc. in Clojure.

However be aware that there is currently no way to docstring the definterface.

Unless you have a need for Java compatibility though, you should look into clojure protocols

If this is about exposing Clojure code to Java it seems the best approach is to write the interface in Java and implement it in Clojure as seen in https://github.com/puredanger/clojure-from-java.