Clojure - deftype 被忽略 - 无法解析测试中的类名
我正在 Clojure 中测试 deftype
和 defprotocol
,但我有点困惑。
我用的是莱宁根。我的核心文件 (src/core.clj
) 如下所示:
(defprotocol Speaker
(say [speaker message]))
(deftype Person [name]
Speaker
(say [_ message] (str name ": " message)))
我的测试文件 (test/core.clj
) 如下所示:
(deftest people-can-talk
(is (= "Peter: hello" (say (Person. "Peter") "hello"))))
当我执行该测试时(使用 < code>lein test) 我收到以下错误:
Exception in thread "main" java.lang.IllegalArgumentException: Unable to resolve classname: Person, compiling:(my-project/test/core.clj:2)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:6416)
at clojure.lang.Compiler.analyze(Compiler.java:6216)
我相信它告诉我 Person
未定义。但确实如此!如果不是,Clojure 不会抛出错误吗?我是否遗漏了一些明显的语法错误?
我正在使用 clojure 1.3.0 。
I'm testing deftype
and defprotocol
in Clojure, but I'm in a bit of a pickle.
I'm using leiningen. My core file (src/core.clj
) looks like this:
(defprotocol Speaker
(say [speaker message]))
(deftype Person [name]
Speaker
(say [_ message] (str name ": " message)))
My test file (test/core.clj
) looks like this:
(deftest people-can-talk
(is (= "Peter: hello" (say (Person. "Peter") "hello"))))
When I execute that test (with lein test
) I get the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Unable to resolve classname: Person, compiling:(my-project/test/core.clj:2)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:6416)
at clojure.lang.Compiler.analyze(Compiler.java:6216)
I believe it is telling me that Person
isn't defined. But it is! If it wasn't, wouldn't Clojure have thrown an error? Is there some obvious syntax error I'm missing?
I'm using clojure 1.3.0 .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要在另一个包/文件中使用 deftype 定义的类,您需要(导入)它们,或提供完整的包名称,例如
(core.Person."Peter")
- 或任何名称空间core.clj 是。此外,“lein test”仅加载测试文件。如果您想引用另一个文件中的任何内容,则需要在测试文件中使用或要求该文件。
To use classes defined by deftype in another package/file, you need to (import) them, or provide the full package name, like
(core.Person. "Peter")
- or whatever the namespace for core.clj is.Additionally, "lein test" only loads the test files. If you want to refer to anything in another file, you'd need to use or require that file in the test file.
您的建议没有为我解决类引用错误。但实现如下所述的“工厂方法”是一种解决方法:
关于此问题的另一个 stackoverflow 答案
You suggestion did not resolve the class reference error for me. But implementing a "factory method" as described below is a work-around:
another stackoverflow answer on this issue