Kotlin - Nullable

Nullable
  • "String?" in return type shows the function may return null
  • API caller need use "?." to prevent 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"
}

Post action if not 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
}

Double bang operation
  • "!!." will throw exception when return value was 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
}

Default value if null
package examples

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

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

Compute differently when null and not-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
}


沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...