How to check “instanceof ” class in kotlin?

2019-02-21 06:38发布

In kotlin class, I have method parameter as object (See kotlin doc here ) for class type T. As object I am passing different classes when I am calling method. In Java we can able to compare class using instanceof of object which class it is.

So I want to check and compare at runtime which Class it is?

How can I check instanceof class in kotlin?

5条回答
ら.Afraid
2楼-- · 2019-02-21 07:30

Use is.

if (myInstance is String) { ... }

or the reverse !is

if (myInstance !is String) { ... }
查看更多
一夜七次
3楼-- · 2019-02-21 07:33

Try using keyword called is Official page reference

if (obj is String) {
    // obj is a String
}
if (obj !is String) {
    // // obj is not a String
}
查看更多
叼着烟拽天下
4楼-- · 2019-02-21 07:40

We can check whether an object conforms to a given type at runtime by using the is operator or its negated form !is.

Example:

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

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

Another Example in case of Custom Object:

Let, I have an obj of type CustomObject.

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

if (obj !is CustomObject) {
    print("obj is not of type CustomObject")
}
查看更多
The star\"
5楼-- · 2019-02-21 07:45

Combining when and is:

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

copied from official documentation

查看更多
劳资没心,怎么记你
6楼-- · 2019-02-21 07:45

You can use 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 */ }
}
查看更多
登录 后发表回答