9

Since recently, (I think it's since I converted my code to kotlin but not sure), Android Studio show me a warning when I write

if (myValue.compareTo(BigDecimal.ZERO) > 0)

The message say "Call replaceable with binary operator" and replace my code with

if (myValue > BigDecimal.ZERO)

I noticed I also use

if (myValue.compareTo(BigDecimal.ZERO) == 0

But this time I got no warning and if I try to replace it, it doesn't work

if (myValue == BigDecimal.ZERO) // DOES NOT WORK

Why does > ZERO work but not == ZERO? Why every thread that I saw on stackoverflow (for example this) recommand using compareTo but > ZERO work and is recommended by Android Studio?

Matt Klein
  • 7,856
  • 6
  • 45
  • 46
Bencri
  • 1,173
  • 1
  • 7
  • 22

1 Answers1

8

tl;dr:

  • val1 > val2 -> val1.compareTo(val2) > 0
  • val1 == val2 -> val1.equals(val2)
  • BigDecimal.equals(...) does not work the way you expect it to.

This happens because Kotlin replaces the binary operators >, >=, <, and <= with a call to .compareTo, so val1 > val2 is exactly the same as val1.compareTo(val2) > 0.

However, the issue is that val1 == val2 is replaced with a call to .equals, and BigDecimal.equals does not behave the way you think it should. The "correct" way to check for being equal is what you already had, which is val1.compareTo(val2) == 0

You can read a discussion that Kotlin contributors had on this issue starting in 2016 over here.

Matt Klein
  • 7,856
  • 6
  • 45
  • 46
  • I would like to simplify it, although the code docs for BigDecimal.compareTo say this: "This method is provided in preference to individual methods for each of the six boolean comparison operators". – Rick Tilley Apr 19 '22 at 13:22