October 13, 2008

NumberFormatException

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:

Alf said...
This comment has been removed by the author.
Alf said...

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

helium said...

In that case you could simply write

private def parseBoolean(s: String): Boolean =
s != null &&
s.toLowerCase == "true";

Dustin Woods said...

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);

mateusz.fiołka said...

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.