结合Clojure defprotocol和defrecord

Ral*_*lph 6 protocols clojure

据我所知,如果我想定义一个defprotocol只能由一个实现的协议()defrecord,我仍然必须首先定义协议,然后定义defrecord实现它的协议:

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

(defrecord ARecord [a-field b-field]
  AProtocol
  (a-method [this] ...)
  (b-method [this that] ...))
Run Code Online (Sandbox Code Playgroud)

有没有办法将两者结合起来,也许是用"匿名"协议?

ama*_*loy 11

不要这样做.您的记录实现的"私有"或"匿名"协议只是在具有更好选项的语言中重新构建无意义的OOP版本.定义一个对您的记录进行操作的常规旧函数; 它没有理由必须与它们物理连接.

如果你以后想要将它重构成一个协议......它很容易!客户端将无法区分,因为协议函数调用看起来就像常规函数调用.