如何检查kotlin中的“instanceof”类?

在kotlin类中,对于类typesT ,我有作为对象的方法参数(请参见kotlin doc)。 作为对象,我正在调用方法时传递不同的类。 在Java中,我们可以使用对象的instanceof来比较哪个类是类。

所以我想在运行时检查和比较它是哪个类?

我如何检查kotlin中的instanceof类?

使用is

 if (myInstance is String) { ... } 

或者相反!is

 if (myInstance !is String) { ... } 

我们可以通过使用is运算符或其否定forms!is来检查对象是否在运行时符合给定的types。

例:

 if (obj is String) { print(obj.length) } if (obj !is String) { print("Not a String") } 

自定义对象情况下的另一个示例:

让我有一个typesCustomObjectobj

 if (obj is CustomObject) { print("obj is of type CustomObject") } if (obj !is CustomObject) { print("obj is not of type CustomObject") } 

你可以使用的is

 class B val a: A = A() if (a is A) { /* do something */ } when (a) { someValue -> { /* do something */ } is B -> { /* do something */ } else -> { /* do something */ } } 

尝试使用关键字调用is 官方页面参考

 if (obj is String) { // obj is a String } if (obj !is String) { // // obj is not a String } 

结合whenis

 when (x) { is Int -> print(x + 1) is String -> print(x.length + 1) is IntArray -> print(x.sum()) } 

从官方文档复制