chris
chris

Reputation: 2513

Reflection warning despite type hint to Java constructor in Clojure

The following code gives me a reflection warning in spite of the type hint.

(set! *warn-on-reflection* true)

(IllegalArgumentException.
  ^String (with-out-str (print "hi")))

The warning:

Reflection warning ... 
call to java.lang.IllegalArgumentException ctor 
can't be resolved.

The code has been extracted and simplified from a more complex example where pretty printing an arbitrary object is performed within the with-out-str. I am using Clojure 1.10.0.

Upvotes: 2

Views: 313

Answers (3)

amalloy
amalloy

Reputation: 92117

This is CLJ-865. It's not specific to with-out-str: adding a type hint to any form which is a macro invocation will typically discard it. The typical workaround is the one in your answer: define a local saving the value, artificially introducing an non-macro form to annotate.

Upvotes: 6

Carcigenicate
Carcigenicate

Reputation: 45806

I'm not sure the cause, but I'll note it can be fixed with a call to str:

(IllegalArgumentException. (str (with-out-str (print "hi"))))

It seems to be something to do with try?:

(set! *warn-on-reflection* true)

(IllegalArgumentException. ^String (try "" (finally "")))

Reflection warning, C:\Users\slomi\AppData\Local\Temp\form-init3916067866461493959.clj:3:1 - call to java.lang.IllegalArgumentException ctor can't be resolved.

Upvotes: 1

chris
chris

Reputation: 2513

Carcigenicate's insight into the cause inspired me to try the following which also works.

(let [m (with-out-str (print "hi"))]
  (IllegalArgumentException.
   ^String m ))

Upvotes: 1

Related Questions