Displaying objects in REPL: Clojure equivalent of Java's toString?

254 views
Skip to first unread message

Dragan Djuric

unread,
Aug 1, 2013, 5:49:14 PM8/1/13
to clo...@googlegroups.com
I have some custom types defined using deftype and I am trying to enable a human-friendly string representation of these types in repl. Something similar to #<Atom@123 "value">. How to do that in Clojure without redefining toString? It seems that Clojure use a different way to achieve this for atoms and refs, I just can't find what.

Laurent PETIT

unread,
Aug 1, 2013, 6:04:47 PM8/1/13
to clo...@googlegroups.com
I think you have to provide methods for multimethods print-dup and
print-method:

https://github.com/clojure/clojure/blob/c6756a8bab137128c8119add29a25b0a88509900/src/clj/clojure/core.clj#L3311

2013/8/1 Dragan Djuric <drag...@gmail.com>:
> --
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your
> first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
> ---
> You received this message because you are subscribed to the Google Groups
> "Clojure" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to clojure+u...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Armando Blancas

unread,
Aug 1, 2013, 11:07:37 PM8/1/13
to clo...@googlegroups.com
Adding to that... have a look at the implemented methods in core_print.clj. The print-method will get called on print and println with your instance as the first argument. In this example prints a pair type; since elements can be anything it just calls print on each.

(deftype Pair [fst snd])
(defmethod print-method Pair [r, ^java.io.Writer w]
  (.write w "Pair(")
  (print (.fst r))
  (.write w ",")
  (print (.snd r))
  (.write w ")"))

Dragan Djuric

unread,
Aug 2, 2013, 9:51:54 AM8/2/13
to clo...@googlegroups.com
Thanks a lot, guys :)
Reply all
Reply to author
Forward
0 new messages