Constants in Clojure

Constants in programming are immutable values that do not change during the execution of a program. Here’s how you can work with constants in Clojure.

(ns constants-example
  (:require [clojure.pprint :refer [pprint]]))

(def s "constant")

(defn -main []
  (println s)
  
  ;; A constant statement can appear anywhere a var statement can.
  (def n 500000000)
  (println (/ 3e20 n))
  
  ;; A numeric constant has no type until it’s given one, such as by an explicit conversion.
  (println (long (/ 3e20 n)))
  
  ;; A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. 
  ;; For example, here Math/sin expects a float.
  (println (Math/sin n)))

To run the program, save the code in a file named constants_example.clj and run it using the Clojure command-line tools.

$ clj -M -m constants-example
constant
6.0E11
600000000000
-0.28470407323754404

In the above Clojure code:

  • We define a namespace constants-example and require the clojure.pprint library for printing.
  • The constant s is defined using def.
  • The -main function prints the constant s.
  • Another constant n is defined and used in arithmetic with arbitrary precision.
  • The result is explicitly converted to long before printing.
  • Finally, the Math/sin function is used to demonstrate type conversion in context.