Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Truth: string to boolean inconsistency?

Tags:

groovy

In groovy:

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

Can anyone clarify this behavior?

like image 582
Raphael Avatar asked Jan 19 '12 17:01

Raphael


2 Answers

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.

like image 172
Dónal Avatar answered Oct 14 '22 10:10

Dónal


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() 
like image 20
jaetzold Avatar answered Oct 14 '22 11:10

jaetzold