Hi Nicolas,

The macro works fine. The problem is that the REPL tries to print the
result (which is the var you created) and the print multimethod does
not know what to do with your custom type, and the default method
throws an exception.

user=> (defbar fuz (+ 1 1))
java.lang.ClassCastException: clojure.lang.Var cannot be cast to
clojure.lang.IObj
user=> fuz
2
user=> (meta (var fuz))
{:ns #<Namespace user>, :name fuz, :file "NO_SOURCE_PATH", :line 133,
:type :user/MyType}
user=> (print (var fuz))
java.lang.ClassCastException: clojure.lang.Var cannot be cast to
clojure.lang.IObj (NO_SOURCE_FILE:0)

user=> (defmethod print-method ::MyType [o w] (.write w "hi"))
#<MultiFn clojure.lang.mult...@79884a40>
user=> (print (var fuz))
hinil
user=> (defbar zzz (+ 2 3))
hi
user=> zzz
5
user=> (meta (var zzz))
{:ns #<Namespace user>, :name zzz, :file "NO_SOURCE_PATH", :line 148,
:type :user/MyType}


(defmethod print-method :default [o, #^Writer w]
  (print-method (vary-meta o #(dissoc % :type)) w))

user=> (vary-meta (var fuz) #(dissoc % :type))
java.lang.ClassCastException: clojure.lang.Var cannot be cast to
clojure.lang.IObj (NO_SOURCE_FILE:0)




Regards,
Tim.



2010/1/9 Nicolas Buduroi <nbudu...@gmail.com>:
> Hi, I'm using macros to define special vars (w/ a keyword as type) to
> retrieve them later with ns-utils/ns-vars and filter them. I don't
> know if this technique is recommended or if there's some better way to
> achieve this, but there's something weird happening when we try to
> evaluate the var defined at the REPL. For example, if you run this
> code:
>
> (defmacro defbar [foo & body]
>  `(def ~(with-meta foo {:type ::MyType})
>     (eval ~...@body)))
>
> (defbar baz (+ 1 1))
>
> It throws a ClassCastException: "clojure.lang.Var cannot be cast to
> clojure.lang.IObj", which is an error I encountered often and never
> truly understood. Can somebody help me find out what I'm missing?
>
> Thanks
>
> - budu
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clojure@googlegroups.com
> Note that posts from new members are moderated - please be patient with your 
> first post.
> To unsubscribe from this group, send email to
> clojure+unsubscr...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
>
-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to