Ralph
Ralph

Reputation: 32304

Combining Clojure defprotocol and defrecord

As far as I can tell, if I want to define a protocol (defprotocol) that will only be implemented by one defrecord, I still have to define the protocol first, then define the defrecord that implements it:

(defprotocol AProtocol
  (a-method [this])
  (b-method [this that]))

(defrecord ARecord [a-field b-field]
  AProtocol
  (a-method [this] ...)
  (b-method [this that] ...))

Is there no way to combine the two, perhaps with an "anonymous" protocol?

Upvotes: 6

Views: 3903

Answers (2)

amalloy
amalloy

Reputation: 92147

Don't do this. A "private" or "anonymous" protocol that your record implements is just reinventing a pointless version of OOP in a language that has better options. Define a regular old function that operates on your records; there's no reason it has to be physically attached to them.

If you later want to refactor it to be a protocol instead...it's easy! The client won't be able to tell the difference, because protocol function calls look just like regular function calls.

Upvotes: 13

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91617

Yes that is completely correct :)

The main reason for this would be if you expect others to want to extend your protocol later.

Upvotes: 4

Related Questions