在kotlin类中,我有方法参数作为对象(参见kotlin文档这里)的类类型t作为对象,当我调用方法时,我传递不同的类。 在Java中,我们可以使用对象的instanceof来比较它是哪个类。
所以我想在运行时检查和比较它是哪个类?
如何在kotlin检查instanceof类?
在kotlin类中,我有方法参数作为对象(参见kotlin文档这里)的类类型t作为对象,当我调用方法时,我传递不同的类。 在Java中,我们可以使用对象的instanceof来比较它是哪个类。
所以我想在运行时检查和比较它是哪个类?
如何在kotlin检查instanceof类?
当前回答
when和is的结合:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
摘自官方文件
其他回答
使用。
if (myInstance is String) { ... }
或者正好相反
if (myInstance !is String) { ... }
尝试使用名为is的关键字 官方页面参考
if (obj is String) {
// obj is a String
}
if (obj !is String) {
// // obj is not a String
}
其他解决方案:KOTLIN
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment?.tag == "MyFragment")
{}
你可以这样检查
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 */ }
}