Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {})))
like image 579
fraxture Avatar asked Jan 12 '21 00:01

fraxture


People also ask

Do the CL Clojure tools create artifacts?

No. The clojure tools are focused on a) building classpaths and b) launching clojure programs. They do not (and will not) create artifacts, deploy artifacts, etc.

How to add to the front of a collection in Clojure?

Vectors (indexed) are designed to expand at the back. As the user, you should consider this when you choose which data structure to use. In Clojure, vectors are used with much greater frequency. If your goal is specifically to "add to the front of the collection", then the appropriate function to use is cons, which will always add to the front.

How does conj work in Clojure?

Most Clojure data structure operations, including conj (conjoin), are designed to give the user a performance expectation. With conj, the expectation is that insertion should happen at the place where this operation is efficient. Lists (as linked lists) can make a constant time insertion only at the front.

What is reflective access in Clojure?

One of the areas affected by this change in Java is reflective access. Clojure uses reflection when it encounters a Java interop call without sufficient type information about the target object or the function arguments. For example: (def fac (javax.xml.stream.XMLInputFactory/newInstance)) (.createXMLStreamReader fac (java.io.StringReader. ""))


1 Answers

You need to add a hint to the constructor argument:

(let [^java.util.Map m {}]
  (new java.util.HashMap m))
like image 91
Lee Avatar answered Oct 07 '22 05:10

Lee