How to check “instanceof ” class in kotlin?
在kotlin类中,我将方法参数作为类类型T的对象(请参见kotlin doc此处)。作为对象,当我调用method时,我传递了不同的类。
在Java中,我们可以使用对象的
所以我想在运行时检查并比较它是哪个类?
如何检查Kotlin中的
使用
1 | if (myInstance is String) { ... } |
或反向
1 | if (myInstance !is String) { ... } |
组合
1 2 3 4 5 | when (x) { is Int -> print(x + 1) is String -> print(x.length + 1) is IntArray -> print(x.sum()) } |
从官方文件复制
我们可以使用
例:
1 2 3 4 5 6 7 | if (obj is String) { print(obj.length) } if (obj !is String) { print("Not a String") } |
自定义对象的另一个示例:
我有一个
1 2 3 4 5 6 7 | if (obj is CustomObject) { print("obj is of type CustomObject") } if (obj !is CustomObject) { print("obj is not of type CustomObject") } |
您可以使用
1 2 3 4 5 6 7 8 | class B val a: A = A() if (a is A) { /* do something */ } when (a) { someValue -> { /* do something */ } is B -> { /* do something */ } else -> { /* do something */ } } |
尝试使用名为
官方页面参考
1 2 3 4 5 6 | if (obj is String) { // obj is a String } if (obj !is String) { // // obj is not a String } |
其他解决方案:KOTLIN
1 2 3 4 | val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container) if (fragment?.tag =="MyFragment") {} |
你可以这样检查
1 | private var mActivity : Activity? = null |
然后
1 2 3 4 5 6 7 8 | override fun onAttach(context: Context?) { super.onAttach(context) if (context is MainActivity){ mActivity = context } } |
您可以在https://kotlinlang.org/docs/reference/typecasts.html上阅读Kotlin文档。我们可以使用
1 2 3 4 5 6 7 8 | 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 } |
然后在主要功能中,我尝试打印并显示在终端上:
1 2 3 4 5 6 7 8 | fun main() { val stringResult = getResult("Kotlin") val intResult = getResult(100) // TODO 2 println(stringResult) println(intResult) } |
这是输出
1 2 | 6 500 |