Created
June 29, 2022 05:44
-
-
Save sohang3112/8281a8ea8b9482f55df1113f87fe8c23 to your computer and use it in GitHub Desktop.
Declaratively initialize an object having setter methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defmacro with-attrs [obj-exp & args] | |
`(doto ~obj-exp | |
~@(for [[key val] (partition 2 args)] | |
(list (->> key | |
name | |
capitalize | |
(str ".set") | |
symbol) | |
val)))) | |
;; For example, this code: | |
(with-attrs (SomeObject.) | |
:name (str "Hello" "World") | |
:type 'SomeType | |
:description (format "Description: %s" "a description")) | |
;; ...expands to (via macroexpand-1): | |
(doto (SomeObject.) | |
(.setName (str "Hello World") | |
(.setType 'SomeType) | |
(.setDescription (format "Description: %s" "a description")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment