我是 Clojure 新手。我定义了以下协议
(ns com.mycompany.protocols.tools)
(defprotocol Tool
(test-ov [this] [this user-id]))
我尝试了两种实现方式。
实现方式1:
(ns com.mycompany.resources.tools
(:require [com.mycompany.protocols.tools :as proto]))
(deftype MyTool [config]
proto/Tool
(test-ov
([this user-id]
1111 )
([this]
(test-ov this nil)))
......
我遇到错误
LOAD FAILURE for com.mycompany.myservice.resources.utils
clojure.lang.Compiler$CompilerException: java.lang.Exception: Unsupported binding form: 1111, compiling:(com/mycompany/resources/mytool.clj:198:1)
java.lang.Exception: Unsupported binding form: 1111
......
实现方式2:
(ns com.mycompany.resources.tools
(:require [com.mycompany.protocols.tools :as proto]))
(deftype MyTool [config]
proto/Tool
(test-ov
[this user-id]
1111 )
(test-ov
[this]
(test-ov this nil))
......
我遇到错误
LOAD FAILURE for com.mycompany.test.myservice.resources.utils
clojure.lang.Compiler$CompilerException: java.lang.RuntimeException: Unable to resolve symbol: test-ov in this context, compiling:(com/mycompany/myservice/resources/mytool.clj:335:6)
java.lang.RuntimeException: Unable to resolve symbol: test-ov in this context
......
那么如何从定义了协议的“原始”函数中调用重写函数呢?请帮忙。谢谢。
根据defprotocol的文档,第二种方法是正确的:
(deftype MyTool [config]
proto/Tool
(test-ov [this user-id] 1111)
(test-ov [this] (test-ov this nil)))
问题在于调用
(test-ov this nil)
,因为符号 test-ov
在此上下文中未解析。要么写 (proto/test-ov this nil)
要么在 require 形式中显式引用 var:(:require [com.mycompany.protocols.tools :as proto :refer [test-ov])