2012-04-16 41 views
3

也許明顯,但鑑於該代碼(從http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/reify):具體化,的ToString

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

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

爲什麼會出現這樣的輸出?

#<ui$reify_str$reify__4722__4727 foo> 

相反的:

foo 

我正在ClojureCLR在Windows中,如果有幫助。謝謝!

+0

看起來像這樣:http://stackoverflow.com/questions/5306015/equivilent-javas-tostring-for-clojure-functions是相關的 – sw1nn 2012-04-16 19:19:18

回答

5

你的基本問題是Clojure REPL使用print-method而不是.toString。您必須爲您的類型定義print-method。這對於通用類型來說有點煩人,因爲它使它們變得冗長。你必須做這樣的事情:

(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)) 

(我只在香草Clojure的測試,但我認爲這是ClojureCLR相同)

在這一點上,不過,你」因爲你每次都重新定義方法,所以創建一個實際的類型而不是重新定義會更好。 (我想你可以做一些全局狀態來避免必要性,但是......你可以明白爲什麼定義類型可能更可取。)

+0

這是行得通的,只是測試過它。順便說一下,我上面粘貼的代碼片段也是這樣,*如果我將它包裝在(str ...)的調用中(我想調用ToString方法,而println調用print-method)。 – 2012-04-17 19:59:28