在kotlin类中,我有方法参数作为对象(参见kotlin文档这里)的类类型t作为对象,当我调用方法时,我传递不同的类。 在Java中,我们可以使用对象的instanceof来比较它是哪个类。

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

如何在kotlin检查instanceof类?


当前回答

其他解决方案:KOTLIN

val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)

if (fragment?.tag == "MyFragment")
{}

其他回答

你可以在这里阅读Kotlin文档https://kotlinlang.org/docs/reference/typecasts.html。我们可以在运行时使用is操作符或其否定形式!is来检查对象是否符合给定类型,例如使用is:

fun <T> getResult(args: T): Int {
    if (args is String){ //check if argumen is String
        return args.toString().length
    }else if (args is Int){ //check if argumen is int
        return args.hashCode().times(5)
    }
    return 0
}

然后在main函数中,我尝试打印并在终端上显示它:

fun main() {
    val stringResult = getResult("Kotlin")
    val intResult = getResult(100)

    // TODO 2
    println(stringResult)
    println(intResult)
}

这是输出

6
500

你可以用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 */ }
}

使用。

if (myInstance is String) { ... }

或者正好相反

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

你可以这样检查

 private var mActivity : Activity? = null

then

 override fun onAttach(context: Context?) {
    super.onAttach(context)

    if (context is MainActivity){
        mActivity = context
    }

}

when和is的结合:

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

摘自官方文件