clojuresymbolsvardereferenceresolve

Can I avoid a second symbol lookup in Clojure resolve?


I need to do a lot of string-to-symbol-value processing, but some of the strings will not resolve to symbols. I have written the following (example) code to test to see if a given string resolves to a known symbol, before dereferencing the var to get the symbol's value.

(if (resolve (symbol "A")) @(resolve (symbol "A"))  ;; If the resolve of "A" works, deref it.
    false)                                          ;; If "A" doesn't resolve to a var, return false.

Maybe I think about things too much. I'm concerned about having to do the

(resolve (symbol "A"))

twice many times. Is there a clever way I can perform this "test-for-nil-and-deref-it-if-not," only once? Maybe a "safe" deref function that doesn't generate a runtime error when dereferencing nil? Or should I just not worry about performance in this code? Maybe the compiler's clever?


Solution

  • You can try the when-let macro to only call deref when the result of resolve is present:

    (when-let [resolved (resolve (symbol "A"))]
      @resolved)
    

    Or a shorter version with some->:

    (some-> "A" symbol resolve deref)