将自定义类型转换为字符串

时间:2018-02-09 10:21:56

标签: string clojurescript

在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的自定义字符串表示形式?

1 个答案:

答案 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"
相关问题