pepejeria — 2007-05-24T12:59:05-04:00 — #1
Lets say that we have a String with the value "false" or "true". Lets now cast this String to a boolean value. In Java it would be
Boolean fun = new Boolean("true");
// notFun = true
The above will only be false if false, NaN, null, 0 or an empty String is provided, everything else will return true.
So the only way to cast a String with the values "true" or "false" is to use eval...
var snowing = eval("false");
Anybody has another way to do the cast?
kyberfabrikken — 2007-05-24T13:16:29-04:00 — #2
var stringRepresentation = "false";
var booleanRepresentation = (stringRepresentation == "true");
pepejeria — 2007-05-24T13:21:09-04:00 — #3
Thanks, yes, thats one way to do it, buy not really a cast. Its a result from a comparison. That is what I wanted to avoid.
kyberfabrikken — 2007-05-24T14:33:05-04:00 — #4
The thing is; What you want to do is not really a type cast. You want to interpret the value of the variable -- not simply change the type of it.
pepejeria — 2007-05-24T17:16:28-04:00 — #5
mrhoo — 2007-05-24T17:26:10-04:00 — #6
This does not change the string, but returns the evaled value of the string.
If you hate eval you can define all the values-
if(this==='false') return false;
stereofrog — 2007-05-25T04:54:38-04:00 — #7
Technically, what java does is not a typecast, but the Boolean(Stirng) constructor, that arbitrarily interprets the string "true" as boolean true. Nice? I find this kind of code rather stinky
Boolean a = new Boolean("true"); // true
Boolean b = new Boolean("true "); // FALSE
pepejeria — 2007-05-25T07:50:28-04:00 — #8
I guess that it calls parseBoolean internally, but that is another story.
Anyway, thanks for the answers everybody
pepejeria — 2007-05-26T11:34:54-04:00 — #9
No, I don't hate eval, I use it as the last resort. Extending native objects would though be more something that I dislike.