首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提供意外空指针的Clojure multimethod

提供意外空指针的Clojure multimethod
EN

Stack Overflow用户
提问于 2014-05-17 18:15:41
回答 1查看 183关注 0票数 1

我很难让Clojure中的多方法像我所期望的那样工作。我的代码的精馏如下。

代码语言:javascript
复制
(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的方法,但是我得到一个空指针异常。即使是我能想到的对multimethod的最简单调用,也给出了一个空指针:

代码语言:javascript
复制
(defmulti simpleMulti :key)

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

(simpleMulti {:key "basic"})

然而,位于这里的clojure文档中的示例工作得很好。我是不是做错了什么基本的事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-17 18:28:57

据我所知,它起作用了。

给定的

代码语言:javascript
复制
(defmulti testMulti (fn [_ command] (:command-type command)))

(defmethod testMulti :one [game command] (str "blah"))

(defmethod testMulti :default [& args] "Cannot understand")

然后

代码语言:javascript
复制
(testMulti "something" {:command-type :one})
; "blah"

(testMulti "something" {:command-type :two})
; "Cannot understand"

(testMulti "something" 5)
; "Cannot understand"

如预期的那样。

在重新运行上述程序之前,我会重置REPL。

这个简单的例子也很管用。给定的

代码语言:javascript
复制
(defmulti simpleMulti :key)

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

然后

代码语言:javascript
复制
(simpleMulti {:key "basic"})
; "basic value"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23714622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档