How to make a record from a sequence of values

后端 未结 5 1306
执笔经年
执笔经年 2020-12-20 13:38

I have a simple record definition, for example

(defrecord User [name email place])

What is the best way to make a record having it\'s value

5条回答
  •  旧时难觅i
    2020-12-20 13:53

    Warning: works only for literal sequables! (see Mihał's comment)

    Try this macro:

    (defmacro instantiate [klass values] 
            `(new ~klass ~@values))
    

    If you expand it with:

    (macroexpand '(instantiate User ["John" "john@example.com" "Dreamland"]))

    you'll get this:

    (new User "John" "john@example.com" "Dreamland")

    which is basically what you need.

    And you can use it for instantiating other record types, or Java classes. Basically, this is just a class constructor that takes a one sequence of parameters instead of many parameters.

提交回复
热议问题