Search code examples
groovy

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?


Solution

  • 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.