Nullable
  • 回傳型別中的 "String?" 表示這個函式可能回傳 null
  • 呼叫端需要用 "?." 來避免 NullPointerException
package examples

fun main() {
    println(getString(true))         // null
    println(getString(false))        // hello
    println(getString(true)?.length) // null
    println(getString(false)?.length) // 5
}

fun getString(isNull: Boolean): String? {
    if (isNull) return null
    return "hello"
}

非 null 時的後續操作
package examples

fun main() {
    println(getInt(false)?.let {
        println(it)
        it + 100
    })
}

fun getInt(isNull:Boolean): Int? {
    if (isNull) return null
    else return 5
}

雙驚嘆號運算子
  • "!!." 會在回傳值為 null 時拋出例外
package examples

fun main() {
    println(getInt(false)!!.let {
        println(it)
        it + 100
    })
    println(getInt(true)!!.let { // throw kotlin.KotlinNullPointerException due to !!.
        println(it)
        it + 100
    })
}

fun getInt(isNull:Boolean): Int? {
    if (isNull) return null
    else return 5
}

null 時的預設值
package examples

fun main() {
    println(getInt(true) ?: 100) // print 100
}

fun getInt(isNull:Boolean): Int? {
    if (isNull) return null
    else return 5
}

null 與非 null 時分別處理
package examples

fun main() {
    // print null and kotlin.Unit because println returns Unit
    println(getInt(true) ?.and(100) ?: println("null"))
}

fun getInt(isNull:Boolean): Int? {
    if (isNull) return null
    else return 5
}


Tags:

Updated: