Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

Groovy Truth: string to boolean inconsistency?

In groovy:

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

Can anyone clarify this behavior?

question from:https://stackoverflow.com/questions/8930325/groovy-truth-string-to-boolean-inconsistency

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Both of these

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

instantiate a java.lang.Boolean using the constructor that takes a single String argument. According to the javadocs, the rule is:

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.

In both of the cases above, the String does not match 'true' (case-insensitively), so the Boolean created is false.

By contrast 'test' as Boolean follows the Groovy language rules for coercion to a boolean, which allows you to write:

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

For a String, the rule is that if it's empty or null, it evaluates to false, otherwise true.

I agree that this could be considered a bit inconsistent, but given a choice between consistency with the constuctor of java.lang.Boolean and utility, I think they were right to choose the latter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...