All of the following assertions are true
.
def obj = ["XXX"]
assert true && obj // OK
assert obj // OK
assert ![] // OK
Why is coercion not working in the following one?
assert true == obj // List is NOT coerced to true
All of the following assertions are true
.
def obj = ["XXX"]
assert true && obj // OK
assert obj // OK
assert ![] // OK
Why is coercion not working in the following one?
assert true == obj // List is NOT coerced to true
Because the == operator doesn't expect boolean operands.
Coercion is applied in the second case because the && operator expects boolean operands, and in the third case because assert expects a boolean operand. But the == operator accepts operands of any type and returns false if either the type or the value are different.
An empty collection is false when evaluated in a boolean context (AKA falsey), so
assert ![]
evaluates to true
and the assertion passes.
The '==' operator is translated to an equals(Object o) method call, so it works with any kind of Object, not just Boolean, so there's no reason for coercion to boolean.