clojureclojure-java-interop

How can I add a typehint in clojure to fix "ctor can't be resolved" reflection warning, i.e call to a constructor?


The following example function, which uses Clojure's special form for java interop to call a class constructor, causes a reflection warning:

(defn test-reflection-err []
  (new java.util.HashMap {}))

That message reads:

Reflection warning, /Users/ethan/Projects/scicloj/tablecloth.time/src/tablecloth/time/index.clj:26:3 - call to java.util.HashMap ctor can't be resolved.

I've tried placing type hints to avoid this but am not sure where to place them to prevent the reflection error. Does anyone know how to do this?

I've tried:

(defn test-reflection-err []
  (^TreeMap new java.util.HashMap {}))

and

(defn test-reflection-err []
  (doto ^TreeMap (new java.util.HashMap {})))

Solution

  • You need to add a hint to the constructor argument:

    (let [^java.util.Map m {}]
      (new java.util.HashMap m))