简体   繁体   English

如何在Clojure中的函数上覆盖toString?

[英]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. 举例来说,假设我将StringBuilder包装在一个函数中,以便可以在Clojure中更轻松地使用它。 I can easily make the no-arg version of the function call toString on the buffer eg 我可以轻松地在缓冲区上使函数调用toString的无参数版本

(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. 这是完全可行的,但是,我想知道如何在函数本身上覆盖.toString(),以便返回StringBuilder或已关闭的任何其他对象的状态。

You could try using https://github.com/technomancy/serializable-fn , which makes functions include their closed-over scope when they print. 您可以尝试使用https://github.com/technomancy/serializable-fn ,这会使函数在打印时包括其封闭范围。 It will print the pr-str of the stringbuilder, though, which may or may not be exactly what you want. 但是,它将打印stringbuilder的pr-str,它可能与您想要的不一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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