我很难让Clojure中的多种方法像我期望的那样工作。我的代码的提炼如下。
(defn commandType [_ command] (:command-type command))
(defmulti testMulti commandType)
(defmethod testMulti :one [game command] (str "blah"))
(defmethod testMulti :default [& args] "Cannot understand")
(testMulti "something" {:command-type :one})
(commandType "something" {:command-type :one})
现在我希望在这个参数上调用方法commandType当然会返回:一个应该将它发送到第一个defmethod而是得到一个空指针异常。即使是最简单的多方法调用我也能得到一个空指针:
(defmulti simpleMulti :key)
(defmethod simpleMulti "basic" [params] "basic value")
(simpleMulti {:key "basic"})
然而位于here的clojure文档中的示例运行正常。有什么根本我做错了吗?
答案 0 :(得分:1)
据我所见,它有效。
鉴于
(defmulti testMulti (fn [_ command] (:command-type command)))
(defmethod testMulti :one [game command] (str "blah"))
(defmethod testMulti :default [& args] "Cannot understand")
然后
(testMulti "something" {:command-type :one})
; "blah"
(testMulti "something" {:command-type :two})
; "Cannot understand"
(testMulti "something" 5)
; "Cannot understand"
正如所料。
我在重新运行上面之前重置了REPL。
这个简单的例子也有效。鉴于
(defmulti simpleMulti :key)
(defmethod simpleMulti "basic" [params] "basic value")
然后
(simpleMulti {:key "basic"})
; "basic value"