加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy Truth:string到boolean不一致?

发布时间:2020-12-14 16:38:15 所属栏目:大数据 来源:网络整理
导读:在groovy: println 'test' as Boolean //trueprintln 'test'.toBoolean() //falseprintln new Boolean('test') //false 有人可以澄清这个行为吗? 解决方法 这两个 println 'test'.toBoolean() //falseprintln new Boolean('test') //false 使用接受单个Str
在groovy:

println 'test' as Boolean //true
println 'test'.toBoolean() //false
println new Boolean('test') //false

有人可以澄清这个行为吗?

解决方法

这两个

println 'test'.toBoolean() //false
println new Boolean('test') //false

使用接受单个String参数的构造函数来实例化一个java.lang.Boolean。根据the javadocs,规则是:

Allocates a Boolean object representing the value true if the string argument is not null and is equal,ignoring case,to the string “true”. Otherwise,allocate a Boolean object representing the value false.

在上述两种情况下,String不匹配“true”(不区分大小写),因此创建的布尔值为false。

相比之下,“测试”为布尔遵循了coercion to a boolean的Groovy语言规则,允许您写:

if ('hello') {
    println 'this string is truthy'
}

对于String,规则是如果它为空或为空,则它的计算结果为false,否则为true。

我同意这可以被认为有点不一致,但是考虑到与java.lang.Boolean和实用程序的一致性的一致性,我认为他们选择后者是正确的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读