Switch in Clojure

Switch statements express conditionals across many branches.

Here’s a basic switch.

(defn main []
  (let [i 2]
    (println "Write" i "as")
    (case i
      1 (println "one")
      2 (println "two")
      3 (println "three"))))

(main)

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

(defn main []
  (let [today (.getDay (js/Date.))]
    (case today
      0 1 (println "It's the weekend")
      (println "It's a weekday"))))

(main)

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

(defn main []
  (let [hour (.getHours (js/Date.))]
    (if (< hour 12)
      (println "It's before noon")
      (println "It's after noon"))))

(main)

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable i will have the type corresponding to its clause.

(defn what-am-i [i]
  (cond
    (boolean? i) (println "I'm a bool")
    (integer? i) (println "I'm an int")
    :else (println (str "Don't know type " (type i)))))

(what-am-i true)
(what-am-i 1)
(what-am-i "hey")

To run the program, put the code in a .clj file and use clojure to execute it.

$ clojure -M switch.clj
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string