Reify, ToString

Perhaps obvious, but given this code (from http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/reify ):

(defn reify-str []
  (let [f "foo"]
    (reify Object
      (ToString [this] f))))

(defn -main [& args]
  (println (reify-str))
  (System.Console/ReadLine))

Why am I getting this conclusion?

#<ui$reify_str$reify__4722__4727 foo>

Instead:

foo

I am running ClojureCLR on Windows if this helps. Thank!

+3
source share
1 answer

The main problem is that Clojure REPL uses print-method, not .toString. You must specify print-methodfor your type. This is a bit annoying to reified types as it makes them kind of verbose. You will need to do something like this:

(defn reify-str []
  (let [f "foo"
        r (reify Object
            (ToString [this] f))]
    (defmethod clojure.core/print-method (type r) [this writer] 
      (print-simple f writer))
    r))

(I only tested this in vanilla Clojure, but I think it is the same in ClojureCLR.)

, reifying, . ( , - , , ... , , .)

+5

All Articles