Clojure deftype和协议

时间:2014-05-15 00:13:21

标签: clojure clojure-protocol

我的(ns处理程序)

中有这个Clojure代码
(defprotocol ActionHandler
  (handle [params session]))

(defrecord Response [status headers body])

(deftype AHandler []
  ActionHandler
  (handle [params session]
          (Response. 200 {"Content-Type" "text/plain"} "Yuppi, a-handler works")))


(deftype BHandler []
  ActionHandler
  (handle [params session]
          (Response. 200 {"Content-Type" "text/plain"} "YES, the b-handler is ON")))

(deftype CHandler []
  ActionHandler
  (handle [params session]
          (Response. 200 {"Content-Type" "text/plain"} "C is GOOD, it's GOOD!")))

在我的core.clj中,我得到了这段代码(省略了几行和命名空间):

    (handle the-action-handler params session)

-action-handler 是deftype Handler之一的有效实例。 当我尝试编译时,我收到此错误:

java.lang.IllegalArgumentException: No single method: handle of interface: handlers.ActionHandler found for function: handle of protocol: ActionHandler

当无效数量的参数传递到协议函数时,我确实读到了关于误导性错误消息,但是,您可以看到并非如此。

可能是什么问题?有什么建议? 格雷格

1 个答案:

答案 0 :(得分:0)

我相信你传递的是两个而不是一个。发生的事情是协议方法的第一个参数是this参数。

试试这个

(defprotocol ActionHandler
  (handle [this params session]))

(defrecord Response [status headers body])

(deftype AHandler []
  ActionHandler
  (handle [this params session]
          (Response. 200 {"Content-Type" "text/plain"} "Yuppi, a-handler works")))


(deftype BHandler []
  ActionHandler
  (handle [this params session]
          (Response. 200 {"Content-Type" "text/plain"} "YES, the b-handler is ON")))

(deftype CHandler []
  ActionHandler
  (handle [this params session]
          (Response. 200 {"Content-Type" "text/plain"} "C is GOOD, it's GOOD!")))