Search code examples
syntaxclojuredeftype

Clojure - deftype ignored - unable to resolve classname on tests


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 .


Solution

  • 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.