On Wed, Aug 18, 2010 at 11:09 AM, Brian Hurt <[email protected]> wrote:
> Consider the following bit of code:
>
> (let [ x (new java.lang.Boolean false) ] (if x "trouble" "ok"))
The Javadoc for Boolean has something to say on this subject[1]
as does the following excerpt from Fogus' book The Joy of
Clojure:
Don't create Boolean objects
----------------------------
It is possible to create an object that looks a lot like, but is
not actually, `false`.
Java has left a little landmine for you here, so take a moment to
look at it so that you can step past it gingerly and get on with
your life:
(def evil-false (Boolean. "false")) ; NEVER do this
This creates a new instance of Boolean -- and that's already
wrong! Since there are only two possible values of Boolean, an
instance of each has already been made for you -- they're named
`true` and `false`. But here you've gone and done it anyway,
created a new instance of Boolean and stored it in a Var named
`evil-false`. It looks like false:
evil-false
;=> false
Sometimes it even acts like false:
(= false evil-false)
;=> true
But once it gains your trust, it will show you just how wicked it
is by acting like `true`:
(if evil-false :truthy :falsey)
;=> :truthy
Java's own documentation warns against the creation of this evil
thing, and now you've been warned again. If you just want to
parse a string, use Boolean's static method instead of its
constructor. This is the right way:
(if (Boolean/valueOf "false") :truthy :falsey)
;=> :falsey
--Chouser
http://joyofclojure.com/
1:
http://download-llnw.oracle.com/javase/1.5.0/docs/api/java/lang/Boolean.html#Boolean%28boolean%29
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en