foxlog
4/11/2018 - 6:14 AM

A brief example of protocols and records in Clojure clj

A brief example of protocols and records in Clojure clj

;; A protocol with a single method
(defprotocol Waggable
  (wag [x]))

;; A record that implements that protocol
(defrecord Dog [name]
  Waggable
  (wag [x]
    (prn (str (:name x)
              " wagged their tail"))))

;; Call that method
(wag (->Dog "Derek"))

;; A record that doesn't implement the protocol
(defrecord Cat [name])

;; Extended to implement the protocol
(extend-protocol Waggable
  Cat
  (wag [x]
    (prn "Cats don't wag")))

;; And then call that method
(wag (->Cat "Arnold"))