Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 714
toanphan19 Avatar asked Apr 07 '26 06:04

toanphan19


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"
like image 55
Martin Půda Avatar answered Apr 16 '26 15:04

Martin Půda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!