Scala: Elegant conversion of a string into a boolean

Viewed 57642

In Java you can write Boolean.valueOf(myString). However in Scala, java.lang.Boolean is hidden by scala.Boolean which lacks this function. It's easy enough to switch to using the original Java version of a boolean, but that just doesn't seem right.

So what is the one-line, canonical solution in Scala for extracting true from a string?

6 Answers

Scala 2.13 introduced String::toBooleanOption, which combined to Option::getOrElse, provides a safe way to extract a Boolean as a String:

"true".toBooleanOption.getOrElse(false)  // true
"false".toBooleanOption.getOrElse(false) // false
"oups".toBooleanOption.getOrElse(false)  // false

I've been having fun with this today, mapping a 1/0 set of values to boolean. I had to revert back to Spark 1.4.1, and I finally got it working with:

Try(if (p(11).toString == "1" || p(11).toString == "true") true else false).getOrElse(false)) 

where p(11) is the dataframe field

my previous version didn't have the "Try", this works, other ways of doing it are available ...

Related