Truthy and Falsy
One notable aspect of Clojure’s handling of Booleans is that the language is willing to treat any value as a Boolean. This, for example is a perfectly good if:
| (if 1 |
| "I like science fiction!" |
| "I like mysteries!") |
As is this:
| (if "hello" |
| "I like science fiction!" |
| "I like mysteries!") |
And even this:
| (if [1 2 3] |
| "I like science fiction!" |
| "I like mysteries!") |
Not only are these good if statements, but in all three cases the winner is science fiction. The rule is simple: in an if statement and any other Boolean context, only false and nil get treated as false. Everything else is treated as true. Thus this expression will announce a love of mysteries:
| (if false "I like scifi!" "I like mysteries!" ... |
Get Getting Clojure now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.