Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Writing your own constructor function is probably the way to go. As Arthur Ulfeldt said, you then have a function you can use as a function (e.g. with <code>apply</code>) rather than a Java-interop constructor call.</p> <p>With your own constructor function you can also do argument validation or supply default arguments. You gain another level of abstraction to work with; you can define <code>make-user</code> to return a hash-map for quick development, and if you later decide to change to records, you can do so without breaking everything. You can write constructors with multiple arities, or that take keyword arguments, or do any number of other things.</p> <pre><code>(defn- default-user [name] (str (.toLowerCase name) "@example.com")) (defn make-user ([name] (make-user name nil nil)) ([name place] (make-user name nil place)) ([name user place] (when-not name (throw (Exception. "Required argument `name` missing/empty."))) (let [user (or user (default-user name))] (User. name user place)))) (defn make-user-keyword-args [&amp; {:keys [name user place]}] (make-user name user place)) (defn make-user-from-hashmap [args] (apply make-user (map args [:name :user :place]))) user&gt; (apply make-user ["John" "john@example.com" "Somewhere"]) #:user.User{:name "John", :email "john@example.com", :place "Somewhere"} user&gt; (make-user "John") #:user.User{:name "John", :email "john@example.com", :place nil} user&gt; (make-user-keyword-args :place "Somewhere" :name "John") #:user.User{:name "John", :email "john@example.com", :place "Somewhere"} user&gt; (make-user-from-hashmap {:user "foo"}) ; Evaluation aborted. ; java.lang.Exception: Required argument `name` missing/empty. </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload