242

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?

pRaNaY
  • 24,642
  • 24
  • 96
  • 146

8 Answers8

446

Use is.

if (myInstance is String) { ... }

or the reverse !is

if (myInstance !is String) { ... }
Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
nhaarman
  • 98,571
  • 55
  • 246
  • 278
  • 3
    This only works when the instance object is created from a Kotlin class. This will not work if the instance was created using newInstance() from something like SomeClass::class.java – Johann Aug 22 '21 at 15:30
  • 1
    @androiddev why is that? – nhaarman Aug 22 '21 at 21:12
  • 2
    No idea. I tried it but it doesn't work. Some quirk with the way Kotlin interacts with Java. However, you can use SomeClass.isInstance(someObject), which does work. – Johann Aug 23 '21 at 07:08
69

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

methodsignature
  • 4,152
  • 2
  • 20
  • 21
34

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")
}
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
  • 4
    Note one other nice thing here: inside the block of the `if`, `obj` is automatically cast to `String`. So you can use properties such as `length` directly, without the need to explicitly cast `obj` to `String` inside the block. – Jesper May 22 '17 at 06:20
  • Also, nice opportunity to use an else statement ;) – Juan Nunez Jan 29 '21 at 15:20
  • What if i want to differentiate two classes where one extends the other e.g LinearLayoutManager & GridLayoutManager – Isaac Obella Apr 19 '21 at 09:45
9

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
}
Rashi Karanpuria
  • 1,605
  • 1
  • 11
  • 18
Terril Thomas
  • 1,486
  • 13
  • 32
  • It is great thing to give answer with official doc. But it is better practices to add sample code in answer, it is helpful if link was dead. Thanks for the answer. – pRaNaY May 21 '17 at 17:03
9

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 */ }
}
ice1000
  • 6,406
  • 4
  • 39
  • 85
5

You can check like this

 private var mActivity : Activity? = null

then

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

    if (context is MainActivity){
        mActivity = context
    }

}
The Bala
  • 1,313
  • 1
  • 15
  • 23
3

You can read Kotlin Documentation here https://kotlinlang.org/docs/reference/typecasts.html . We can check whether an object conforms to a given type at runtime by using the is operator or its negated form !is, for the example using 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
}

then in main function i try to print and show it on terminal :

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

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

This is the output

6
500
Cevin Ways
  • 984
  • 11
  • 13
-8

Other solution : KOTLIN

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

if (fragment?.tag == "MyFragment")
{}
Álvaro Agüero
  • 4,494
  • 1
  • 42
  • 39