Reputation: 2513
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
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
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
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