gpt4 book ai didi

Groovy 真相 : string to boolean inconsistency?

转载 作者:行者123 更新时间:2023-12-03 01:55:22 28 4
gpt4 key购买 nike

在常规中:

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

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

最佳答案

这两个

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

使用采用单个字符串参数的构造函数实例化一个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.

在上述两种情况下,字符串与“true”不匹配(不区分大小写),因此创建的 bool 值为 false。

相比之下,'test' as Boolean 遵循 coercion to a boolean 的 Groovy 语言规则,它允许您编写:

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

For a String ,规则是如果它为空或 null,则计算结果为 false,否则为 true。

我同意这可能被认为有点不一致,但考虑到与 java.lang.Boolean 的构造函数的一致性和实用性之间的选择,我认为他们选择后者是正确的。

关于Groovy 真相 : string to boolean inconsistency?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8930325/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com