Kotlin筆記 類型檢查和轉(zhuǎn)型

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容