Alex Rivera | Logout

Java's switch equivalent in Clojure?

Asked 2011-12-02T06:09:03.213
38

Is there an equivalent for Java's switch construct in Clojure? If yes, what is it? If no, do we have to use if else ladder to achieve it?

Edit
Report

1 Answer

42

case is a good option as pointed out by Jan

cond is also very useful in many related circumstances, particularly if you want to switch on the basis of evaluating a range of different conditional expressions, e.g.

(defn account-message [balance]
  (cond 
    (< balance 0) "Overdrawn!"
    (< balance 100) "Low balance"
    (> balance 1000000) "Rich as creosote"
    :else "Good balance"))

Note that the result of cond is determined by the first matching expression, so a negative balance will display "Overdrawn!" even though it also matches the low balance case.

[I have edited the code - removed the extra bracket at the end to make it work]

answered 2011-12-02T10:05:31.493

Your Answer