在groovy:
println 'test' as Boolean //true
println 'test'.toBoolean() //false
println new Boolean('test') //false
Run Code Online (Sandbox Code Playgroud)
任何人都可以澄清这种行为吗?
Dón*_*nal 38
这两个
println 'test'.toBoolean() //false
println new Boolean('test') //false
Run Code Online (Sandbox Code Playgroud)
java.lang.Boolean使用带有单个String参数的构造函数实例化a .根据javadocs,规则是:
如果字符串参数不为null且与字符串"true"相等(忽略大小写),则分配表示值true的Boolean对象.否则,分配一个表示值false的Boolean对象.
在上述两种情况中,String都不匹配'true'(不区分大小写),因此创建的Boolean为false.
相比之下'test' as Boolean,Groovy语言规则强制为布尔值,允许你写:
if ('hello') {
println 'this string is truthy'
}
Run Code Online (Sandbox Code Playgroud)
对于String,规则是如果它为空或null,则计算结果为false,否则为true.
我同意这可能被认为有点不一致,但考虑到与构造函数java.lang.Boolean和实用程序的一致性之间的选择,我认为选择后者是正确的.
小智 18
唐是对的:
'test' as Boolean遵循Groovy语言规则强制到布尔值
这也被称为"Groovy真理".
但是String.toBoolean()在groovy中,不只是构造一个以String作为参数的布尔值.从String.toBoolean()上的groovy api文档:
String.toBoolean()将给定的字符串转换为布尔对象.如果修剪后的字符串为"true","y"或"1"(忽略大小写),则结果为true,否则为false.
assert "y".toBoolean()
assert 'TRUE'.toBoolean()
assert ' trUe '.toBoolean()
assert " y".toBoolean()
assert "1".toBoolean()
assert ! 'other'.toBoolean()
assert ! '0'.toBoolean()
assert ! 'no'.toBoolean()
assert ! ' FalSe'.toBoolean()
Run Code Online (Sandbox Code Playgroud)