Skip to content

Instantly share code, notes, and snippets.

@sohang3112
Created June 29, 2022 05:44
Show Gist options
  • Save sohang3112/8281a8ea8b9482f55df1113f87fe8c23 to your computer and use it in GitHub Desktop.
Save sohang3112/8281a8ea8b9482f55df1113f87fe8c23 to your computer and use it in GitHub Desktop.
Declaratively initialize an object having setter methods
(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