Java Programming Tutorials

Java programming tutorials with many code examples!

Clojure switch case


One of the first control flow statements in many programming languages is switch-case. Clojure switch case is a bit different that in other programming languages. The following example show how.


There are a couple of functions in Clojure that serve as switch case control flow statements. The first one is case:

(defn case-example
  " example"
  (case word
    "saluton" "Esperanto!"
    "hi" "English"

It takes an expression (here word evaluates to itself) and tries to match its result with constant in the first column and returns value from the right column when it matches. Default value can be provided as a single value, without test expression. If default value is not provided and there is no match then IllegalArgumentException is thrown.

Running the example gives:

examples.core> (case-example "saluton")
examples.core> (case-example "aoeu")

The next switch case function in Clojure is cond:

(defn cond-example
  "clojure.core.cond example"
    (< (count p) 8) "too short"
    (< 32 (count p)) "too long"
    :else "ok"))

It takes a number of pairs test expression and a value. When test expression matches the the value is returned. The last expression :else as other keywords evaluates to itself, which is boolean true, and is commonly used to denote default value. Returns nil when there’s no default.

Running the code gives:

examples.core> (cond-example "secret")
"too short"
examples.core> (cond-example "top secret")
examples.core> (cond-example "top secret xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
"too long"

The last one is condp:

(defn condp-example
  "clojure.core.condp example"
  [op a b]
  (condp = op
    '+ (+ a b)
    '- (- a b)
    "Unknown operator"))

Clojure condp macro takes a binary predicate (here =) and an expression (here op) and a number of pairs test-expression,result-expression. For each clause the following expression is evaluated: (pred test-expr expr). So for arguments _’+ 1 2_ it would be (= ‘+ ‘+). When it returns true then result expression is evaluated and returned. Default value is indicated by line without separate test expression. No default value results in IllegalArgumentException when non matches.

Running the example gives:

examples.core> (condp-example '+ 1 2)
examples.core> (condp-example '* 1 2)
"Unknown operator"

Now switching from Java switch-case to Clojure switch-case should be a breeze. ;-)

Was it helpful? Share!