Search code examples
clojure

What is reify in Clojure?


I could not understand the usage of reify function in Clojure. What is it used for in clojure?

Could you provide examples?


Solution

  • reify macro allow to create an anonymous class extending java.lang.Object class and/or implementing specified interfaces/protocols. The API docs don't describe the purpose clearly but rather provide the technical details what that macro does. Java interop documentation provides a brief description of the purpose:

    As of Clojure 1.2, reify is also available for implementing interfaces.

    Even more information can be found in datatypes documentation where you can find a very detailed description what it does and how it compares to proxy:

    While deftype and defrecord define named types, reify defines both an anonymous type and creates an instance of that type. The use case is where you need a one-off implementation of one or more protocols or interfaces and would like to take advantage of the local context. In this respect it is use case similar to proxy, or anonymous inner classes in Java.

    The method bodies of reify are lexical closures, and can refer to the surrounding local scope. reify differs from proxy in that:

    Only protocols or interfaces are supported, no concrete superclass. The method bodies are true methods of the resulting class, not external fns. Invocation of methods on the instance is direct, not using map lookup. No support for dynamic swapping of methods in the method map. The result is better performance than proxy, both in construction and invocation. reify is preferable to proxy in all cases where its constraints are not prohibitive.