89
votes

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
Why not simply use a regular expression?Kevin Meredith
It doesn't sound simple at all.Jaime Hablutzel

6 Answers

154
votes

Ah, I am silly. The answer is myString.toBoolean.

113
votes

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

25
votes

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
11
votes

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.

8
votes

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

1
votes

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 ...