How to check “instanceof ” class in kotlin?

こ雲淡風輕ζ 提交于 2019-12-01 02:02:33
nhaarman

Use is.

if (myInstance is String) { ... }

or the reverse !is

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

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

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

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

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
}

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
    }

}

Other solution : KOTLIN

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!