How to check "instanceof " class in kotlin?

KotlinKotlin Extension

Kotlin Problem Overview


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?

Kotlin Solutions


Solution 1 - Kotlin

Use is.

if (myInstance is String) { ... }

or the reverse !is

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

Solution 2 - Kotlin

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

Solution 3 - Kotlin

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")
}

Solution 4 - Kotlin

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
}

Solution 5 - Kotlin

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 */ }
}

Solution 6 - Kotlin

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

Solution 7 - Kotlin

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
    }

}

Solution 8 - Kotlin

You may compare any class with the following function.

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

// When you use
if("test".isInstanceOf(String.class)) {
    // do something
}

Solution 9 - Kotlin

Other solution : KOTLIN

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpRaNaYView Question on Stackoverflow
Solution 1 - KotlinnhaarmanView Answer on Stackoverflow
Solution 2 - KotlinmethodsignatureView Answer on Stackoverflow
Solution 3 - KotlinAvijit KarmakarView Answer on Stackoverflow
Solution 4 - KotlinTerril ThomasView Answer on Stackoverflow
Solution 5 - Kotlinice1000View Answer on Stackoverflow
Solution 6 - KotlinCevin WaysView Answer on Stackoverflow
Solution 7 - KotlinThe BalaView Answer on Stackoverflow
Solution 8 - KotlinSeigo OhzonoView Answer on Stackoverflow
Solution 9 - KotlinÁlvaro AgüeroView Answer on Stackoverflow