Scala: 将字符串优雅地转换为布尔值

在 Java 中你可以编写 Boolean.valueOf(myString)。但是在 Scala 中,java.lang.Boolean被缺少这个函数的 scala.Boolean隐藏了。切换到使用布尔值的原始 Java 版本是很容易的,但这看起来就是不对。

那么 Scala 中从字符串中提取 true的一行规范解决方案是什么呢?

59074 次浏览

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.

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

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

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

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