Can you extend a type/record to implement the str function in Clojure?

Viewed 75

I have a type Book defined with defrecord, and a function to convert it into a string:

(defrecord Book [title author])
(defn book->string [book] (str (:title book) " by " (:author book))) 

(book->string (->Book "Foo" "Bar"))  ;; "Foo by Bar"

Is it possible to extend the record so that I can call (str (->Book "Foo" "Bar")) instead?

1 Answers

You don't have to extend anything, just overwrite toString method:

(defrecord Book [title author]
  Object
  (toString [_] (str title " by " author)))

Test:

(str (->Book "Foo" "Bar"))
=> "Foo by Bar"
Related