175

在 kotlin 类中,我将方法参数作为类类型T的对象(参见 kotlin doc here ) 。作为对象,我在调用方法时传递了不同的类。在Java中,我们可以使用对象来比较类是哪个类。instanceof

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

如何instanceof在 kotlin 中查看课程?

4

9 回答 9

347

使用is.

if (myInstance is String) { ... }

或相反!is

if (myInstance !is String) { ... }
于 2017-05-21T15:52:32.537 回答
51

结合whenis

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

复制自官方文档

于 2018-01-11T18:08:26.240 回答
21

is我们可以通过使用运算符或其否定形式在运行时检查对象是否符合给定类型!is

例子:

if (obj is String) {
    print(obj.length)
}

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

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

让,我有一个obj类型CustomObject

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

if (obj !is CustomObject) {
    print("obj is not of type CustomObject")
}
于 2017-05-21T15:53:59.597 回答
8

您可以使用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 */ }
}
于 2017-05-21T15:55:42.083 回答
7

尝试使用称为is 官方页面参考的关键字

if (obj is String) {
    // obj is a String
}
if (obj !is String) {
    // // obj is not a String
}
于 2017-05-21T15:53:08.023 回答
3

您可以在此处阅读 Kotlin 文档https://kotlinlang.org/docs/reference/typecasts.htmlis我们可以通过使用运算符或其否定形式在运行时检查对象是否符合给定类型,!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
}

然后在主要功能中,我尝试在终端上打印并显示它:

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

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

这是输出

6
500
于 2019-08-23T07:21:25.690 回答
0

你可以像这样检查

 private var mActivity : Activity? = null

然后

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

    if (context is MainActivity){
        mActivity = context
    }

}
于 2019-03-27T07:56:51.650 回答
-1

您可以将任何类与以下功能进行比较。

fun<T> Any.instanceOf(compared: Class<T>): Boolean {
    return this::class.java == compared
}

// When you use
if("test".isInstanceOf(String.class)) {
    // do something
}
于 2022-01-13T07:32:41.260 回答
-5

其他解决方案:KOTLIN

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

if (fragment?.tag == "MyFragment")
{}
于 2019-05-10T14:44:23.660 回答