1

我很难让 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 在参数上调用,它当然会返回 :one ,它应该将它发送到第一个 defmethod 但我得到一个空指针异常。即使是我能想到的最简单的多方法调用也会给我一个空指针:

(defmulti simpleMulti :key)

(defmethod simpleMulti "basic" [params] "basic value")

(simpleMulti {:key "basic"})

然而,位于此处的 clojure 文档中的示例运行良好。有什么基本的我做错了吗?

4

1 回答 1

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"
于 2014-05-17T18:28:57.493 回答