Search code examples
clojureread-eval-print-loopdeftypeleiningen

deftype failing in lein repl what am I doing wrong?


Per http://www.assembla.com/spaces/clojure/wiki/Datatypes

I should be able to type the following into a lein reply:

(deftype Bar [a b c d e])

(def b (Bar 1 2 3 4 5))

However when I do I get the following output:

java.lang.Exception: Expecting var, but Bar is mapped to class user.Bar (NO_SOURCE_FILE:31)

I'm confused and am a complete newb to clojure all help is appreciated!

NOTE: Tried same code in standard clojure repl and get same problem.

ANSWER: Well I answered my own question with a little additional searching. Turns out the sample was bad. The correct way to instantiate Bar would be:

(def b (Bar. 1 2 3 4 5))

The . at the end of Bar in that usage is important. Still don't quite understand why (so you clojure experts please elaborate if you have time since I would like to know the details ;) ).

Thanks everyone!


Solution

  • I'm not that familiar with deftype, but from what I see you need a point to instantiate a type, try this:

    (deftype Bar [a b c d e])
    
    (def b (Bar. 1 2 3 4 5))
    

    Note it's not Bar, but Bar.. See examples e.g. here:

    This thread seems to indicate this was a change in deftype:

    or, to put it the other way around, the docs on the page you link to seem outdated.

    Hope this helps.