Kilian Obermeier
Kilian Obermeier

Reputation: 7168

How to check if two objects have the same class in 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)

Upvotes: 45

Views: 23186

Answers (1)

zsmb13
zsmb13

Reputation: 89668

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.

Upvotes: 97

Related Questions