Created
November 15, 2012 13:24
-
-
Save cgrand/4078651 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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