Kotlin中的“!!”和“?”有什麼區別?
在本文中,我們將舉一個示例並演示 Kotlin 中 (!!) 和 (?) 的區別。
示例——Kotlin中的“!!”和“?”運算子
Kotlin 提供了一個奇妙的運算子來檢查 NULL 指標異常。每當變數為 NULL 時,它都會丟擲一個 NULL 指標異常而不是破壞程式設計邏輯。
在以下示例中,“test” 的值為 NULL。因此,Kotlin 將丟擲一個 NULL 指標異常而不是破壞邏輯。該示例顯示了“!!”和“?”運算子的不同用法。
fun main(args: Array<String>) { val nullValue: String ?=null // it will print null println("The value is ->"+nullValue?.length) // it will throw the exception println(nullValue!!.length) }
輸出
執行後,將產生以下輸出——
The value is ->null Exception in thread "main" java.lang.NullPointerException at MainKt.main(main.kt:8)
下表總結了區別——
輸入 | <<Val>>?.length | <<Val>>!!.length |
輸入為 null | null | 空指標異常 |
廣告