Groovy Truth: string to boolean inconsistency?
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.
Don is right in that:
'test' as Boolean
follows the Groovy language rules for coercion to a boolean
which is also known as "Groovy truth".
But String.toBoolean()
in groovy does not just construct a Boolean with the String as an argument. From the groovy api docs on String.toBoolean():
String.toBoolean()
Converts the given string into a Boolean object. If the trimmed string is "true", "y" or "1" (ignoring case) then the result is true otherwise it is false.
A few good examples for strings and their conversion with toBoolean():
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()