在kotlin类中,我有方法参数作为对象(参见kotlin文档这里)的类类型t作为对象,当我调用方法时,我传递不同的类。 在Java中,我们可以使用对象的instanceof来比较它是哪个类。
所以我想在运行时检查和比较它是哪个类?
如何在kotlin检查instanceof类?
在kotlin类中,我有方法参数作为对象(参见kotlin文档这里)的类类型t作为对象,当我调用方法时,我传递不同的类。 在Java中,我们可以使用对象的instanceof来比较它是哪个类。
所以我想在运行时检查和比较它是哪个类?
如何在kotlin检查instanceof类?
当前回答
你可以用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 */ }
}
其他回答
你可以这样检查
private var mActivity : Activity? = null
then
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is MainActivity){
mActivity = context
}
}
你可以用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 */ }
}
其他解决方案:KOTLIN
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment?.tag == "MyFragment")
{}
可以在运行时使用is操作符或其否定形式!is来检查对象是否符合给定类型。
例子:
if (obj is String) {
print(obj.length)
}
if (obj !is String) {
print("Not a String")
}
自定义对象的另一个例子:
我有一个CustomObject类型的obj。
if (obj is CustomObject) {
print("obj is of type CustomObject")
}
if (obj !is CustomObject) {
print("obj is not of type CustomObject")
}
when和is的结合:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
摘自官方文件