Java's switch equivalent in Clojure?

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?


Try the case macro:

(case (+ 2 3)
  6 "error"
  5 "ok")

or with default value

(case (+ 2 3)
  5 "ok"

Remember that according to the documentation

The test-constants are not evaluated. They must be compile-time literals, and need not be quoted. (...)

See more examples at ClojureDocs.

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]
    (< 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]

Need Your Help

Multiple select case in a select query

sql postgresql stored-procedures plpgsql select-case

I'm beginning in postgres and I have an issue regarding multiple select case in a select query.

why am I inserting multiple spaces into my list

java regex list parsing

I'm reading from a txt file, which contains a paragraph, and I'm parsing the words and inserting them into a list; however, I'm inserting spaces also. Somehow, my regex is do not seem to work every...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.