Skip to content

fix: Try not to fail when comparing different types [DHIS2-21115]#94

Merged
enricocolasante merged 1 commit intomainfrom
DHIS2-21115
Mar 16, 2026
Merged

fix: Try not to fail when comparing different types [DHIS2-21115]#94
enricocolasante merged 1 commit intomainfrom
DHIS2-21115

Conversation

@enricocolasante
Copy link
Copy Markdown
Collaborator

@enricocolasante enricocolasante commented Mar 12, 2026

Fix equality operator coercion for mixed types

Changes

BinaryOperator.equal — Reworked the type coercion priority for the == and != operators:

  • Number takes priority over Boolean: when either operand is a Number, both sides are coerced to numbers before comparing. This aligns with JavaScript == semantics — true becomes 1.0, false becomes 0.0, so 1 == true is true but 2 == true is false.
  • Non-numeric strings no longer throw: comparing a number with a string that cannot be parsed as a number (e.g. '', 'hello') now returns false instead of throwing a NumberFormatException. This is handled by the new tryToNumber helper.
  • Boolean+String fallback: when neither operand is a number, the boolean coercion path applies. Strings are coerced via String.toBoolean(), meaning any string other than "true" (case-insensitive) is treated as false.

Removed behaviour

  • 2.1 == false previously threw IllegalArgumentException: Could not coerce Double '2.1' to Boolean. It now returns false, since the number path takes priority and 2.1 != 0.0.

@sonarqubecloud
Copy link
Copy Markdown

@enricocolasante enricocolasante requested a review from jbee March 12, 2026 13:24
Copy link
Copy Markdown
Collaborator

@jbee jbee left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking for some time that always making a numeric comparison if one side is a number is not fully correct as you might miss that coercion to what the other side might want to be might be successful but I think it does work because any type where that would make a difference can be coerced to a number so doing it that way around comes out the same.

@enricocolasante enricocolasante merged commit 2a8b1e2 into main Mar 16, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants