is and !is 操作符
is和!is可以用來檢查一個實例是否屬于一種類型
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)過is檢查的變量不用顯示的轉(zhuǎn)型(自動轉(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之間,編譯器無法保證變量不變,則不會做自動轉(zhuǎn)換
- val local variable
- val properties
- var local variable
- var properties
as操作符
通過as轉(zhuǎn)型失敗時會拋出異常,as?轉(zhuǎn)型失敗會返回null
val x: String = y as String
val x: String? = y as? String