Skip to content

Instantly share code, notes, and snippets.

@Chouser
Created February 24, 2010 19:02
Show Gist options
  • Save Chouser/313728 to your computer and use it in GitHub Desktop.
Save Chouser/313728 to your computer and use it in GitHub Desktop.
leveraging call-site caching for getter access
(defn message-map [msg1]
(reify
clojure.lang.IDeref
(deref [] msg1)
clojure.lang.IKeywordLookup
(getLookupThunk [k]
(let [getter (->> (name k)
(replace-by #"(?:^|-)(.)" #(.toUpperCase (nth % 1)))
(str "get")
symbol)
msgmap (gensym)
msg-hinted (with-meta `(deref ~msgmap)
{:tag (symbol (.getName (class msg1)))})]
(prn :did k)
(eval `(reify clojure.lang.ILookupThunk
(get [~msgmap] (. ~msg-hinted ~getter))))))))
(def msg1 (-> (make-message-builder) (.setId 3) .build))
(def msg2 (-> (make-message-builder) (.setId 6) .build))
(defn test-get-id [m] (:id (message-map m)))
(test-get-id msg1)
; :did :id
;=> 3
(test-get-id msg1)
;=> 3
(test-get-id msg2)
;=> 6
(test-get-id msg2)
;=> 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment