How could we create “instances” of a type or record on the fly
-
04-10-2019 - |
Question
This question is closely related to this one but i think is more general.
Recently i try to create type "instances" on the fly with multimethods (or with a unique function constructor if possible), based in a metadata tag. I linked a type (a java class under the hood) with this tag and then i didnt know how to continue in a elegant way (without eval or java reflection and strings); new is a special form and it's difficult to handle although you use macros.
In seudo-code it would be:
(def my-tagged-data (with-meta my-data {:my-type-tag my-ns.My-Type}))
(def factory-function [tagged-data]
(create (:my-type-tag (meta tagged-data)) tagged-data))
Solution
You can provide factory functions for your types.
(def my-tagged-data (with-meta my-data {:my-type-factory `my-type-factory}))
(defn factory-function
[tagged-data]
(@(resolve (:my-type-factory (meta tagged-data))) tagged-data))
This may or may not be feasible.
OTHER TIPS
I think that you have to use reflection. (Better idea than eval, I think).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow