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?
var stringRepresentation = "false";
var booleanRepresentation = (stringRepresentation == "true");
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.
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.
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;
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
I guess that it calls parseBoolean internally, but that is another story.
Anyway, thanks for the answers everybody
No, I don't hate eval, I use it as the last resort. Extending native objects would though be more something that I dislike.
This topic is now closed. New replies are no longer allowed.