Scala: Elegant conversion of a string into a boolean
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)
.
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.
Ah, I am silly. The answer is myString.toBoolean
.
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