Question

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!

Was it helpful?

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.

OTHER TIPS

There are two ways of achieving what you are attempting to do. First, let's go over the deftype example.

user=> (deftype Bar [a b c d e])
user.Bar
user=> (def b (Bar. 1 2 3 4 5))
#'user/b
user=> (:a b)
nil
user=> (.a b)
1

You'll notice a few things, here. As was mentioned, you need the "." to instantiate your type. Furthermore, you don't get keyword access (":" notation), only field access (again, with a ".").

The other method is by defining a record with defrecord:

user=> (defrecord Bar [a b c d e])
user.Bar
user=> (def b (Bar. 1 3 5 7 9))
#'user/b
user=> (:a b)
1
user=> (.a b)
1

This gives you both field and keyword access. This access is easily nested, as well, should you decide to have one of your fields contain another record.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top