scala> "true".toBoolean
res1: Boolean = true
That's pretty cool. Does it work for "false" too?
scala> "false".toBoolean
res1: Boolean = false
Yeah! Awesome! How does it handle other values, I wonder?
scala> "1".toBoolean
java.lang.NumberFormatException: For input string: "1"
... Err, what?
5 comments:
What I meant to say was, this seems pretty intentional. From the source of RichString.scala (http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_7_2_RC3/src/library/scala/runtime/RichString.scala?view=markup):
private def parseBoolean(s: String): Boolean =
if (s != null) s.toLowerCase match {
case "true" => true
case "false" => false
case _ => throw new NumberFormatException("For input string: \""+s+"\"")
}
else
throw new NumberFormatException("For input string: \"null\"")
Why they would code it like that I beats me.
If it were to match the java.lang.Boolean.Boolean(String) constructor, shouldn't parseBoolean be somthing like:
private def parseBoolean(s: String): Boolean =
if (s != null) s.toLowerCase match {
case "true" => true
case _ => false
}
else false
In that case you could simply write
private def parseBoolean(s: String): Boolean =
s != null &&
s.toLowerCase == "true";
I don't know anything about Scala but why not lean on Java for this one.
private def parseBoolean(s: String): Boolean =
Boolean.valueOf(s);
I think this code is ok. Why would you want to turn "1" into a boolean? It is not C. In Java there is no number => boolean conversion. One thing that could be better is to change the type of the exception. Probably to IllegalArgument or sth like this.
Post a Comment