pRa*_*NaY 63 kotlin kotlin-extension
在科特林类,我的方法参数作为对象(参见科特林文档这里)类型Ť.作为对象,当我调用方法时,我传递不同的类.在Java中,我们可以比较instanceof
它所使用的类的对象的类.
所以我想在运行时检查并比较它是哪一类?
如何检查kotlin中的instanceof类?
nha*_*man 141
使用is
.
if (myInstance is String) { ... }
Run Code Online (Sandbox Code Playgroud)
或者相反 !is
if (myInstance !is String) { ... }
Run Code Online (Sandbox Code Playgroud)
met*_*ure 14
结合when
和is
:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
Run Code Online (Sandbox Code Playgroud)
从官方文档中复制
Avi*_*kar 11
我们可以通过使用is
运算符或其否定形式来检查对象是否在运行时符合给定类型!is
.
例:
if (obj is String) {
print(obj.length)
}
if (obj !is String) {
print("Not a String")
}
Run Code Online (Sandbox Code Playgroud)
自定义对象的另一个示例:
让我,我有一个obj
类型CustomObject
.
if (obj is CustomObject) {
print("obj is of type CustomObject")
}
if (obj !is CustomObject) {
print("obj is not of type CustomObject")
}
Run Code Online (Sandbox Code Playgroud)
Ter*_*mas 10
尝试使用名为is
“官方页面参考”的关键字
if (obj is String) {
// obj is a String
}
if (obj !is String) {
// // obj is not a String
}
Run Code Online (Sandbox Code Playgroud)
你可以使用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 */ }
}
Run Code Online (Sandbox Code Playgroud)
你可以这样检查
private var mActivity : Activity? = null
Run Code Online (Sandbox Code Playgroud)
然后
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is MainActivity){
mActivity = context
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33865 次 |
最近记录: |