Scala: Elegant conversion of a string into a boolean
ScalaScala Problem Overview
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?
Scala Solutions
Solution 1 - Scala
Ah, I am silly. The answer is myString.toBoolean
.
Solution 2 - Scala
How about this:
import scala.util.Try
Try(myString.toBoolean).getOrElse(false)
If the input string does not convert to a valid Boolean value false
is returned as opposed to throwing an exception. This behavior more closely resembles the Java behavior of Boolean.valueOf(myString)
.
Solution 3 - Scala
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
Solution 4 - Scala
Note: Don't write new Boolean(myString)
in Java - always use Boolean.valueOf(myString)
. Using the new
variant unnecessarily creates a Boolean
object; using the valueOf
variant doesn't do this.
Solution 5 - Scala
The problem with myString.toBoolean
is that it will throw an exception if myString.toLowerCase
isn't exactly one of "true"
or "false"
(even extra white space in the string will cause an exception to be thrown).
If you want exactly the same behaviour as java.lang.Boolean.valueOf
, then use it fully qualified, or import Boolean under a different name, eg, import java.lang.{Boolean=>JBoolean}; JBoolean.valueOf(myString)
. Or write your own method that handles your own particular circumstances (eg, you may want "t"
to be true
as well).
Solution 6 - Scala
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 ...