Skip to content

Instantly share code, notes, and snippets.

@cgrand
Created November 15, 2012 13:24
Show Gist options
  • Save cgrand/4078651 to your computer and use it in GitHub Desktop.
Save cgrand/4078651 to your computer and use it in GitHub Desktop.
(defn ensure-initialized [p]
(or (deref p 0 nil) (throw (IllegalStateException. "Method called on half-initialized object."))))
(defmacro reify-let
[name bindings & impls]
(let [p (gensym "p")
delegate (fn [x]
(if (seq? x)
(let [[method args] x]
`(~method ~args (~method (ensure-initialized ~p) ~@(next args))))
x))
shadow (fn [x]
(if (seq? x)
(let [[method args & body] x]
`(~method ~args (let [~(first args) ~name] ~@body)))
x))]
`(let [~p (promise)
~name (reify ~@(map delegate impls))
~@bindings]
(deliver ~p (reify ~@(map shadow impls)))
~name)))
;; usage
(reify-let self
[context-map {:me self}]
MyProtocol
(do-that-thing [this event]
(handle-event context-map event)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment