Clojure多方法给出了意外的空指针



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

(defmulti simpleMulti :key)
(defmethod simpleMulti "basic" [params] "basic value")
(simpleMulti {:key "basic"})

但是这里的clojure文档中的例子工作得很好。我做错了什么根本的事吗?

就我所见,它是有效的。

给定

(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"

最新更新