Search code examples
clojureinstantiationtostringdeftype

What's a good toString method for a deftype'd object in clojure


(deftype Bag [state]
   Object
     (toString [bag]
       (str "Bag???" state)))

I want the toString to look something like

clojure.core=> (def b (Bag. {:apples 1 :bannanas 4}))
#'clojure.core/b
clojure.core=> (str b)
"BAG: {:apples 1 :bannanas 4}"

What is a nice clojurey way of representing that information? Is

"Bag/{:k :v}" 

better? How does the community do you call your toStrings?


Solution

  • The following is for deftype.

    user=> (deftype Bag [state] 
             Object 
             (toString [_] 
               (str "BAG: " (pr-str state))))
    user.Bag
    user=> (def b (Bag. {:apples 1 :bannanas 4}))
    #'user/b
    user=> (str b)
    "BAG: {:bannanas 4, :apples 1}"