Java – why does kotlin use = = for structural equality and introduce = = = for reference equality

In general, every design decision made by kotlin feels great in itself and provides a good java transition As a java developer, you can start writing code, treat kotlin as a more concise Java rather than a template, and then smoothly enter more advanced aspects such as functional programming

However, one thing I want to know is why its designers decided to make = = behave the same as equals, and then introduced = = = as a reference equation check I can imagine trying to involve other Java developers, let them see your kotlin code and think, "Oh no, there are reference checks in all places that should be called equally!"

What is the thinking process of getting rid of Java conventions here? To be clear, I fully understand the difference between = = or equals and = = = in kotlin. I just want to know why

Solution

The main reason may be that object equality is checked much more frequently than object identification, so it should be at least as easy

I haven't seen a clear statement on this yet But members of the kotlin team have a pointer in the kotlin action book Section 4.3 Section 1 introduces the = = operator. First, it describes the comparison of Java and says:

In Java, checking the object ID is simple:

if (firstObj == secondObj)

However, the equality of inspection objects is longer and unclear:

if (firstObj.equals(secondObj))

– or rather, if you don't want to risk NullPointerException:

if ((firstObj == null) ? (secondObj == null) : firstObj.equals(secondObj))

You can see that more pain is typing, and correct (especially when one of the objects is an expression with side effects...)

So it's easy to forget the difference or not be disturbed, but use = = instead (this can lead to subtle, hard to find, and intermittent bites.)

However, kotlin makes the most common operation easier: its = = operator uses equals() to check object equality and is also responsible for null checking This solves the problem of Java 'forgetting to do this'

(although interoperability with java code is obviously a major goal, JetBrains does not limit itself to trying to look like Java; kotlin borrows Java as much as possible, but is not afraid to change things. You can see different ways to deal with variance by using declarations of Val and VaR and trailing types, different ranges and open default values, & C.)

One of kotlin's motivations is to fix many problems in Java (in fact, JetBrains' comparison language first lists "some Java problems mentioned in kotlin") Therefore, this seems to be the main reason behind the change

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>