简体   繁体   中英

How to override toString on a function in Clojure?

For the sake of example, suppose I've wrapped a StringBuilder in a function so I can use it more easily in Clojure. I can easily make the no-arg version of the function call toString on the buffer eg

(defn builder
  ([^StringBuilder sb]
     (fn
       ([] (.toString sb))
       ([& args]
          (doseq [arg args]
            (.append sb arg)))))
  ([] (builder (StringBuilder.))))

This is perfectly workable, however, I wonder how I could just override .toString() on the function itself so I could return the state of the StringBuilder or any other object that I have closed over.

You could try using https://github.com/technomancy/serializable-fn , which makes functions include their closed-over scope when they print. It will print the pr-str of the stringbuilder, though, which may or may not be exactly what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM