Reputation:
I can only find stuff about the inverse; using Clojure to implement Java interfaces. However, I want to write a programme in Clojure and allow one to extend it with Java. For example:
# P.clj
(defprotocol P
(f [a])
(g [a b]))
# I.java
public class I implements P {
public Object f(Object a) { … }
public Object g(Object a, Object b) { … }
}
Also, how would I specify parameter types so I don’t have to use Object
everywhere?
The only option I currently see is using dot-notation and relying on duck typing but I prefer compile-time verification of interface implementation on the Java side.
Upvotes: 8
Views: 295
Reputation: 12883
As Isaac has already said, yes.
However, w/o a source representation, I think it's kind of a horsesh*t claim. Please note, I'm not referring to Isaac's answer when I say that. I'm referring to the way that Clojure works in this case.
If you need Java interop, you might want to stick with boring Java interfaces. I think it would also make it easier to interoperate w/other languages in the JVM too, as it is the least common denominator. I also think it makes it easier to communicate w/non Clojure developers.
Upvotes: 2
Reputation: 16362
Yes, it's quite possible, and just like that.
From the pertinent part of the docs:
defprotocol will automatically generate a corresponding interface, with the same name as the protocol, i.e. given a protocol my.ns/Protocol, an interface my.ns.Protocol. The interface will have methods corresponding to the protocol functions, and the protocol will automatically work with instances of the interface.
And, to answer your question:
A Java client looking to participate in the protocol can do so most efficiently by implementing the protocol-generated interface.
Upvotes: 7