when-let is a Clojure macro for binding one value lexically and evaluating one or more body forms only when that value is logically true. It returns nil when the tested expression is false. section 3.1.2
Use the following contract:
- Write one binding pair, [bind expr]; bind may use destructuring. section 3.1.2
- Evaluate expr, bind its result, and expose that name to the body. section 3.1.2
- Provide multiple body forms when needed; when-let wraps them in an implicit do. section 3.1.2
- Choose if-let when an explicit alternative is required, or when-some when false should count as present. section 3.1.2
Guarding a resource lookup
(defn loc [resource] (when-let [f (io/resource resource)] (count (s/split-lines (slurp f))))) (loc "non-existent") ;; nil (total-loc "non-existent" "clojure/core.clj" "clojure/pprint.clj") ;; 7570 The bound resource is used only when lookup succeeds; missing resources contribute nil, which keep removes. section 3.1.2
Listing 3.3. → Local Binding, Lexical Scope, Conditional Assignment
(defmacro if-let ([bindings then]) ([bindings then else)) (defmacro when-let [bindings & body]) (defmacro if-some ([bindings then]) ([bindings then else)) (defmacro when-some [bindings & body])
Inspect the compact macro signatures for conditional binding and lexical scope. section 3.1.2
