Attaching type hints to a Clojure delayed call -
i'm attempting put handles on java objects aren't available @ compile time, available @ runtime, in vars follows:
(def component-manager (delay (somejavaobject/gethandle))) (if better mechanism delays available, welcome).
when these objects used, reflection warning generated. these frequent, i've tried avoid following:
(def my-handle ^somejavaobject (delay (somejavaobject/gethandle))) unfortunately, reflection warning still generated in case.
modifying references works:
(.foo ^somejavaobject @my-handle) ...but uglifies code substantially.
wrapping in macro adds type hints seems obvious approach:
(def my-handle' (delay (somejavaobject/gethandle))) (defmacro my-handle [] (with-meta '(deref my-handle') {:tag somejavaobject})) ...and looks should right thing:
=> (set! *print-meta* true) => (macroexpand '(my-handle)) ^somejavaobject (deref my-handle') ...but doesn't hold true when rubber hits road:
=> (.foo (my-handle)) reflection warning, no_source_path:1 - reference field foo can't resolved. what's right way this?
i'd offer 2 different solutions:
1. delay
first off, wanted post answer shows how problem can recreated. (as worded, question abstract , cannot run in repl.)
(set! *warn-on-reflection* true) (def rt (delay (runtime/getruntime))) (.availableprocessors @rt) ; reflection warning you mention don't following approach because consider verbose:
(.availableprocessors ^java.lang.runtime @rt) ; no warning i tried following, did not solve reflection warning:
(def rt (delay ^java.lang.runtime (runtime/getruntime))) (.availableprocessors @rt) ; reflection warning conclusion: if want use delay, ankur's answer works great. adapt example:
(def delayed-runtime (delay (runtime/getruntime))) (defn ^java.lang.runtime get-runtime [] @delayed-runtime) (.availableprocessors (get-runtime)) ; no warning 2. memoize
you might consider using memoization, requires less code:
(def ^java.lang.runtime get-runtime (memoize #(runtime/getruntime))) (.availableprocessors (get-runtime)) ; no warning
Comments
Post a Comment