Search code examples
clojure

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.


Solution

  • 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.