In Kotlin, you can check if an object is an instance of a class (including inheritance) using is
myObject is String
But how can you check, if two objects are of the exact same class? I am searching for an analogue to Python's
type(obj1) is type(obj2)
Difference Between == Operator and equals() Method Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.
This can occur through simple assignment, as shown in the following example. Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.
Referential equality ('===') === operator is used to compare the reference of two variable or object. It will only be true if both the objects or variables pointing to the same object. The negated counterpart of === in Kotlin is !== which is used to compare if both the values are not equal to each other.
In Kotlin, == is the default way to compare two objects: it compares their values by calling equals under the hood. Thus, if equals is overridden in your class, you can safely compare its instances using ==. For reference comparison, you can use the === operator, which works exactly the same as == in Java.
You can get the type of an object with ::class
, and compare those:
val sameClass = obj1::class == obj2::class
More specifically, this section of the above documentation describes that ::class
on an object gives you exactly what you want, the exact class of the instance you're calling it on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With