4 ms·
The table of constants leads to this fun example: System.out.println(Integer.valueOf(22) == Integer.valueOf(22)); // true System.out.println(Integer.valueOf(2
by ramblerman 4y ago
The table of constants leads to this fun example:
System.out.println(Integer.valueOf(22) == Integer.valueOf(22)); // true
System.out.println(Integer.valueOf(2200) == Integer.valueOf(2200)); // false
Which is a bit confusing to say the least. I realize one should never be using == with objects, but still.
- matsemann 4y agoThat's another quality of life improvement in Kotlin, == calls the equals method on the objects, not comparing their references. Which is what most java programmers want in 99% of cases. And makes the code more readable, a.equals(b) is harder to read than a == b.
- marginalia_nu 4y agoIn most cases I'd use equals(a, b) in Java (with a static import of Objects.equals). It's both null safe and more readable.
- bzzzt 4y agoI kind of like that behaviour. You're comparing object references and get exactly the expected output instead of some magically overloaded equality operator. If you want that, just use 'equals' ;)
- n4r9 4y agoSimilar thing happens in Python (assuming my knowledge hasn't gone out of date) x = 2 print(x is 2) // true x = 200 print(x is 200) // false
- masklinn 4y agoI think a big difference is Java you have to switch between `==` and `Object.equals` depending whether your type is a primitive (e.g. int) or a reference (e.g. Integer). In Python the cases where you’d be using `is` are a lot more restricted, and a bit of an optimisation (although most style guides will require it in the cases where it makes sense). There’s basically 3 cases where you’d use `is` in Python: - the standard singletons None, True, and False (and for the latter two you’d usually use truthiness anyway) - placeholder singletons (e.g. for default values when you need something other than None) - actual identity check between arbitrary objects (which very rarely happens IME)
- kaba0 4y agoThis will also be “fixed” once Valhalla arrives.