is and !is 操作符
is
和!is
可以用來(lái)檢查一個(gè)實(shí)例是否屬于一種類(lèi)型
if (obj is String) {
print(obj.length)
}
if (obj !is String) { // same as !(obj is String)
print("Not a String")
}
else {
print(obj.length)
}
Kotlin里經(jīng)過(guò)is
檢查的變量不用顯示的轉(zhuǎn)型(自動(dòng)轉(zhuǎn)換)
fun demo(x: Any) {
if (x is String) {
print(x.length) // x is automatically cast to String
}
}
或者
if (x !is String) return
print(x.length) // x is automatically cast to String
或者
&& 和 || 的右邊
// x is automatically cast to string on the right-hand side of `||`
if (x !is String || x.length == 0) return
// x is automatically cast to string on the right-hand side of `&&`
if (x is String && x.length > 0) {
print(x.length) // x is automatically cast to String
}
或者when里
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
如果變量check和usage之間攀甚,編譯器無(wú)法保證變量不變为居,則不會(huì)做自動(dòng)轉(zhuǎn)換
- val local variable
- val properties
- var local variable
- var properties
as操作符
通過(guò)as轉(zhuǎn)型失敗時(shí)會(huì)拋出異常炮叶,as?轉(zhuǎn)型失敗會(huì)返回null
val x: String = y as String
val x: String? = y as? String