Reader Conditionals
Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (84 / 107)
👈 Calling Methods | TOC | Summary 👉
Reader conditionals are the last feature of Clojure that we’ll cover. Clojure has three official dialects, with Clojure JVM, ClojureScript, and Clojure CLR. While core Clojure functions work largely the same across these dialects, some platform-specific code can vary. Reader conditionals were introduced in Clojure 1.7 to allow mixing code that targets multiple platforms in the same source file.
The only rule is that source files using reader conditionals must use the cljc extension. Let’s say we have a util.cljc file that contains some utility functions that use platform-specific interop. For example, let’s write a function to return the current time in milliseconds that can be cross-compiled to Clojure and ClojureScript.
(defn current-time []
#?(:clj (.getTime (java.util.Date.))
:cljs (.getTime (js/Date.))))
The current-time function uses #? syntax to declare a reader conditional and specifies the code that should be emitted for Clojure and ClojureScript using :clj and :cljs keywords, respectively. When the namespace is compiled, code using java.util.Date will be used for Clojure and code using js/Date will be used for ClojureScript.
;; Clojure
(defn current-time []
(.getTime (java.util.Date.)))
;; ClojureScript
(defn…