Scala: Elegant string to boolean conversion

In Java, you can write Boolean.valueOf(myString) . However, in Scala, java.lang.Boolean hides scala.Boolean , which lacks this feature. It's easy enough to switch to using the original Java version of the boolean, but that just doesn't seem right.

So, what is a one-line canonical solution in Scala to extract true from a string?

+54
scala
Sep 24 '09 at 7:28
source share
5 answers

Ah, I'm stupid. The answer is myString.toBoolean .

+96
Sep 24 '09 at 7:33
source share

How about this:

 import scala.util.Try Try(myString.toBoolean).getOrElse(false) 

If the input string is not converted to a valid boolean, false returned, not an exception. This behavior is more like the behavior of Java Boolean.valueOf(myString) .

+67
Mar 21 '13 at 22:21
source share

Note. Do not write new Boolean(myString) in Java - always use Boolean.valueOf(myString) . Using the new option unnecessarily creates a Boolean object; using the valueOf option does not do this.

+10
Sep 24 '09 at 7:31
source share

The problem with myString.toBoolean is that it throws an exception if myString.toLowerCase not exactly one of "true" or "false" (even extra empty space in the line will throw an exception).

If you want the exact same behavior as java.lang.Boolean.valueOf , use it completely, or import Boolean under a different name, for example import java.lang.{Boolean=>JBoolean}; JBoolean.valueOf(myString) import java.lang.{Boolean=>JBoolean}; JBoolean.valueOf(myString) . Or write your own method that handles your own specific circumstances (for example, you might want "t" be true ).

+9
Aug 28 2018-12-12T00:
source share

Today I enjoy this by comparing a set of 1/0 values ​​with a logical one. I had to go back to Spark 1.4.1, and I finally got it working:

 Try(if (p(11).toString == "1" || p(11).toString == "true") true else false).getOrElse(false)) 

where p (11) is the dataframe field

In my previous version there was no "Try", it works, other ways to make it available ...

0
Oct 07 '16 at 15:54
source share



All Articles