How to check if two objects have the same class in

2019-02-21 18:26发布

问题:

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)

回答1:

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.



标签: kotlin