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