Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Java's toString() for Clojure functions

some Java code I'm using invokes toString() on my Clojure function objects, which return something like #<ns$something something.something$something@7ce1eae7>>- I want to return something else...presumably there's a way to include some metadata in the functions so their objects' toString() returns that instead ?

like image 482
gone Avatar asked Mar 14 '11 23:03

gone


1 Answers

If you just want to make the REPL print-out of your objects more meaningful, you can implement a defmethod print-method for the class in question.

Here's a shortened version of some code I've written recently; this makes the REPL print-out of a Selenium-WebDriver WebDriver object more meaningful:

(defmethod print-method WebDriver
[o w]
(print-simple
 (str "#<" "Title: "    (.getTitle o) ", "
           "URL: "      (.getCurrentUrl o) " >")
  w))

This prints out like #<Title: A Title, URL: http://example.com >

Here, WebDriver represents a class; you can just as easily do this for built-in Clojure data structures by implementing print-method for the appropriate class (The Joy of Clojure features a print-method for clojure.lang.PersistentQueue which has no nice representation by default). The o above is the actual object you're dealing with and w is a writer (required by these kinds of print functions).

like image 132
semperos Avatar answered Oct 13 '22 00:10

semperos