Kotlin null safety

In Kotlin a type is non-null by default: a String can never be null, and the compiler enforces it. A nullable type is written with a question mark, String?, and the compiler refuses to call methods on it until you have dealt with the null case. This moves a whole class of NullPointerException errors from run time to compile time.

Kotlin
fun describe(name: String?): String {
    val length = name?.length ?: -1
    return name?.let { "name '$it' has $length characters" } ?: "no name"
}

fun main() {
    println(describe("Ada"))
    println(describe(null))

    val items: List<String?> = listOf("a", null, "c")
    println(items.filterNotNull().joinToString("+"))

    val text: String? = "kotlin"
    println(text!!.uppercase())

    val missing: String? = null
    val result = runCatching { missing!!.length }
    println(result.exceptionOrNull() is NullPointerException)
}
Read the full lesson