Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Scala: Elegant conversion of a string into a boolean

Writer Andrew Henderson

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?

2

6 Answers

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

3

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

1

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

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.

0

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

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

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.