Semantic Gotcha
One of the selling points of protocols is that they are namespaced functions. This mitigates some of the issues of "monkey patching" where someone adds a new function definition to an existing class. In languages where a class is also a namespace, you can run into conflicts if two definitions of a function named get
are added to a class at the same time. Since Clojure's protocol functions are namespaced, each person can define their own my.company.project/get
and open.source.project/get
functions.
However, there is a gotcha. Recall that a protocol also generates a Java interface, and when you extend a protocol in a defrecord
, the generated class will implement the protocol's Java interface. Suppose that we defined two protocols:
1 (ns stadig.dog) 2 3 (defprotocol IDog 4 (emote [this])) 1 (ns stadig.cat) 2 3 (defprotocol ICat 4 (emote [this]))
The following code listings do different things...