Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two objects have the same class in Kotlin?

Tags:

class

kotlin

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) 
like image 888
Kilian Batzner Avatar asked Dec 20 '17 16:12

Kilian Batzner


People also ask

How can you tell if two objects have the same class?

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.

Can you compare two objects of the same class?

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.

How do I compare two classes in Kotlin?

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.

How do you compare objects in Kotlin?

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.


1 Answers

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.

like image 85
zsmb13 Avatar answered Sep 20 '22 13:09

zsmb13