日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Kotlin淺析null操作方法_Android

作者:niuyongzhi ? 更新時間: 2022-10-22 編程語言

1.在java中由于null引起的空指針異常,是一個運行時異常。

在kotlin中為了避免這樣的問題,會在編譯期提示出來,而不是在運行期才報錯。

1)比如我們把null賦值給一個已經被賦值的變量或者定義一個返回null的函數,編譯器就會報錯提示:Null can not be a value of a non-null type String

    var hello = "hello world"
    hello = null
fun getString(): String{
    return null
}

2)如何把null賦值給一個變量,或者函數,帶上一個?這樣編譯器就不會報錯了。

    var hello: String? = "hello world"
    hello = null
fun getString(): String? {
    return null
}

2.安全調用操作符:問號?

為了避免空指針,kotlin不讓我們給非空變量賦值null,但null在Kotlin中依存在,這種情況下,我們可以使用安全操作符 ?來避免發生空指針異常。

當編譯器遇到安全調用操作符時,會去檢查,如果是null,就會跳過函數的執行,而不會拋出異常。

比如下面這幾行代碼,在java中必然會拋出異常,但是在kotlin中會跳過count()函數執行,并返回null,不會拋出異常。

fun main() {
    val str = getString()
    val count = str?.count()
    println(count)
}
fun getString(): String? {
    return null
}

3.非空斷言操作符:!!雙感嘆號

!!又稱為感嘆號操作符,當變量為null時,會拋出空指針異常,NullPointerException

fun main() {
    val str = getString()
    val count = str!!.count()
    println(count)
}
fun getString(): String? {
    return null
}

4.在Kotlin中也可以用if來判斷null的情況

fun main() {
    val str = getString()
    if (str == null) {
        println("null")
    } else {
        val count = str?.count()
        println(count)
    }
}
fun getString(): String? {
    return null
}

5.空合并操作符?:

?: 如何符號左邊的值為null,則使用右邊的值。

下面這行代碼打印的結果就是 hello

fun main() {
    val str = getString() ?: "hello"
    println(str)
}
fun getString(): String? {
    return null
}

6.Kotlin中捕獲異常 try catch

    try {
        val str = getString()
        val count = str!!.count()
        println(count)
    } catch (e: Exception) {
        e.printStackTrace()
    }

原文鏈接:https://blog.csdn.net/niuyongzhi/article/details/126515015

欄目分類
最近更新