In groovy:
println 'test' as Boolean //true
println 'test'.toBoolean() //false
println new Boolean('test') //false
Can anyone clarify this behavior?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Both of these
instantiate a
java.lang.Booleanusing the constructor that takes a single String argument. According to the javadocs, the rule is:In both of the cases above, the String does not match ‘true’ (case-insensitively), so the Boolean created is false.
By contrast
'test' as Booleanfollows the Groovy language rules for coercion to a boolean, which allows you to write: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.Booleanand utility, I think they were right to choose the latter.