在Clojurescript中给出一个自定义数据类型:
(deftype Foo [bar])
我希望能够使用str
宏将此类型转换为字符串。 (str (->Foo "bar"))
的结果始终为"[object Object]"
。通过浏览各种文档和资源,我找到了允许我定义自定义字符串表示的IPrintWithWriter
协议。因此,以下扩展非常接近我正在寻找的内容:
(extend-type Foo
IPrintWithWriter
(-pr-writer [this writer _] (-write writer (str "test:" (.-bar this)))))
实际上,当使用(pr-str (->Foo "bla"))
时,返回值确实是字符串"test:bla"
。但是,str
的返回值仍为"[object Object]"
。
如何为Foo
而不是str
提供pr-str
的自定义字符串表示形式?
答案 0 :(得分:1)
ClojureScript的str
使用传递的对象的Object.toString
方法作为其参数:
(str x) returns x.toString()
您可以为Foo
类型覆盖此方法:
(deftype Foo [bar]
Object
(toString [this]
(str "Test: " bar)))
;; => cljs.user/Foo
(str (->Foo "x"))
;; => "Test: x"