1

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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.