在不同命名空间的不同文件中实现多重方法
Implementing a multimethod in separate files in different namespace
我试图在一个单独的文件中定义一个多方法及其实现。它是这样的:
在文件 1
(ns thing.a.b)
(defn dispatch-fn [x] x)
(defmulti foo dispatch-fn)
在文件 2
(ns thing.a.b.c
(:require [thing.a.b :refer [foo]])
(defmethod foo "hello" [s] s)
(defmethod foo "goodbye" [s] "TATA")
在主文件中,当我调用方法时,我定义了如下内容:
(ns thing.a.e
(:require thing.a.b :as test))
.
.
.
(test/foo "hello")
当我这样做时,我得到一个异常提示 "No method in multimethod 'foo'for dispatch value: hello
我做错了什么?还是不能在单独的文件中定义多方法的实现?
有可能。问题是因为未加载 thing.a.b.c
命名空间。使用前必须加载。
这是一个正确的例子:
(ns thing.a.e
(:require
[thing.a.b.c] ; Here all your defmethods loaded
[thing.a.b :as test]))
(test/foo "hello")
我试图在一个单独的文件中定义一个多方法及其实现。它是这样的: 在文件 1
(ns thing.a.b)
(defn dispatch-fn [x] x)
(defmulti foo dispatch-fn)
在文件 2
(ns thing.a.b.c
(:require [thing.a.b :refer [foo]])
(defmethod foo "hello" [s] s)
(defmethod foo "goodbye" [s] "TATA")
在主文件中,当我调用方法时,我定义了如下内容:
(ns thing.a.e
(:require thing.a.b :as test))
.
.
.
(test/foo "hello")
当我这样做时,我得到一个异常提示 "No method in multimethod 'foo'for dispatch value: hello
我做错了什么?还是不能在单独的文件中定义多方法的实现?
有可能。问题是因为未加载 thing.a.b.c
命名空间。使用前必须加载。
这是一个正确的例子:
(ns thing.a.e
(:require
[thing.a.b.c] ; Here all your defmethods loaded
[thing.a.b :as test]))
(test/foo "hello")