scala string to boolean
To convert a string to a boolean in Scala, you can use the toBoolean
method provided by the String
class. The toBoolean
method returns true
if the string represents a boolean value of "true" (ignoring case), and false
for any other string value.
Here's an example:
val str = "true"
val bool = str.toBoolean
In this example, the variable str
holds the string value "true". By calling the toBoolean
method on str
, we convert it to a boolean value and assign it to the variable bool
. In this case, bool
will be assigned the value true
.
If the string value is not a valid boolean representation, the toBoolean
method will throw a java.lang.IllegalArgumentException
.
val str = "hello"
val bool = str.toBoolean // This will throw an IllegalArgumentException
It's important to note that the toBoolean
method only recognizes the string values "true" and "false" (ignoring case) as valid boolean representations. Any other string value will result in an exception being thrown.