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
}


沒有留言:

張貼留言

Lessons Learned While Using Claude Code Skills

Recently, I started experimenting with Claude Code Skills . I first saw this YouTube video: https://www.youtube.com/watch?v=CEvIs9y1uog ...