【问题标题】:Implementing a multimethod in separate files in different namespace在不同命名空间的单独文件中实现多方法
【发布时间】:2016-07-12 06:13:18
【问题描述】:

我正在尝试在单独的文件中定义多方法及其实现。它是这样的: 在文件 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

我做错了什么?还是不能在单独的文件中定义多方法的实现?

【问题讨论】:

    标签: clojure polymorphism multimethod


    【解决方案1】:

    这是可能的。问题是因为未加载 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      相关资源
      最近更新 更多