Michael Neale
Michael Neale

Reputation: 19468

can I define a java interface in Clojure?

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.

Upvotes: 1

Views: 781

Answers (2)

nha
nha

Reputation: 18005

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.

Upvotes: 0

Jared314
Jared314

Reputation: 5231

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.

Upvotes: 5

Related Questions