Search code examples
clojuremacrosclojure-java-interop

Practical Clojure: macros and Java interop


In Practical Clojure's chapter on Java interop, the authors note the following about the Java interop "syntactic sugar" (e.g. (.method object arguments) instead of (. object method arguments)):

Since these “syntactic sugar” expansions happen in the same compilation phase as macro-expansion, macros that do complex code-generation may need to avoid them and use the new and . (dot) special forms directly.

I don't understand why "syntactic sugar" expansion happening in the same phase as macro expansion is a problem. Is it because there may be issues with the order of expansions?


Solution

  • Macros concerned with generating interop calls typically should use the desugared special form, but that's not because of when desugaring happens, nor is it a problem. And they don't have to: more times than I care to count, I've seen someone write:

    (defmacro call [obj method & args]
      `(~(symbol (str "." (name method))) ~obj ~@args))
    

    which is just a total mess, compared to how it would look with the appropriate tool:

    (defmacro call [obj method & args]
      `(. ~obj ~method ~@args))