【发布时间】:2017-10-21 06:43:06
【问题描述】:
在 kotlin 类中,我将方法参数作为对象(参见 kotlin doc here),用于类类型 T。作为对象,我在调用方法时传递了不同的类。
在 Java 中,我们可以使用对象的instanceof 来比较类是哪个类。
所以我想在运行时检查和比较它是哪个类?
如何在 kotlin 中查看 instanceof 类?
【问题讨论】:
在 kotlin 类中,我将方法参数作为对象(参见 kotlin doc here),用于类类型 T。作为对象,我在调用方法时传递了不同的类。
在 Java 中,我们可以使用对象的instanceof 来比较类是哪个类。
所以我想在运行时检查和比较它是哪个类?
如何在 kotlin 中查看 instanceof 类?
【问题讨论】:
使用is。
if (myInstance is String) { ... }
或相反!is
if (myInstance !is String) { ... }
【讨论】:
结合when和is:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
【讨论】:
我们可以通过使用is 运算符或其取反形式!is 在运行时检查对象是否符合给定类型。
示例:
if (obj is String) {
print(obj.length)
}
if (obj !is String) {
print("Not a String")
}
自定义对象的另一个示例:
让,我有一个obj,类型为CustomObject。
if (obj is CustomObject) {
print("obj is of type CustomObject")
}
if (obj !is CustomObject) {
print("obj is not of type CustomObject")
}
【讨论】:
if 的块内,obj 自动转换为String。所以你可以直接使用length等属性,而不需要在块内显式地将obj转换为String。
你可以使用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 */ }
}
【讨论】:
尝试使用名为is 的关键字
Official page reference
if (obj is String) {
// obj is a String
}
if (obj !is String) {
// // obj is not a String
}
【讨论】:
您可以在 https://kotlinlang.org/docs/reference/typecasts.html 阅读 Kotlin 文档。我们可以通过使用is 运算符或其取反形式!is 来检查对象在运行时是否符合给定类型,例如使用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
}
然后在主函数中我尝试打印并在终端上显示:
fun main() {
val stringResult = getResult("Kotlin")
val intResult = getResult(100)
// TODO 2
println(stringResult)
println(intResult)
}
这是输出
6
500
【讨论】:
你可以这样检查
private var mActivity : Activity? = null
然后
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is MainActivity){
mActivity = context
}
}
【讨论】:
您可以将任何类与以下函数进行比较。
fun<T> Any.instanceOf(compared: Class<T>): Boolean {
return this::class.java == compared
}
// When you use
if("test".isInstanceOf(String.class)) {
// do something
}
【讨论】:
其他解决方案:KOTLIN
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment?.tag == "MyFragment")
{}
【讨论】: