clr

taryn 2025-01-05T13:23:11.217219Z

How do I create a System.Int32 from an integer literal? I cannot put a type hint directly onto the literal (as numeric literals do not support meta) and when I do the following:

(let [^System.Int32 res-status-code 404]
  (set! (. res StatusCode) res-status-code))
I get:
Object of type 'System.Int64' cannot be converted to type 'System.Int32'.
StatusCode is a property of type Int32.

taryn 2025-01-06T13:38:52.068979Z

Thank you dm!

dmiller 2025-01-05T17:14:13.139279Z

Wrap the 404 with int:

(let [^System.Int32 x 404] (class x))  ; => System.Int64
(let [^System.Int32 x (int 404)] (class x))  ; => System.Int32
This is problem with Clojure generally, not just ClojureCLR. Type hints are just hints. They generally serve to get rid of reflection. However, you can still pass in bad things.
(set! *warn-on-reflection* true)

(defn f [x] (.ToUpper x))  ;; prints reflection warning:  reference to field/property ToUpper can't be resolved (target class is unknown)

(defn g [^String x] (.ToUpper x))   ; => #'user/g, no reflection warning

(g 12)  ; => InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.String'.
At least in the situation you face, the invocation of int gets you the right type of value to pass in.