KtKotlin · Lesson 2 of 8

Null Safety

The billion-dollar mistake, fixed in the type system. In Kotlin, String and String? are different types — and the compiler refuses code that could throw a NullPointerException.

Kotlin
fun main() {
    var name: String = "Ada"
    // name = null              // compile error — String can't be null

    var nickname: String? = null    // String? CAN be null

    // println(nickname.length)  // compile error: might be null

    // Safe call — returns null instead of crashing:
    println(nickname?.length)       // null

    // Elvis operator — default when null:
    val len = nickname?.length ?: 0

    // Chains short-circuit on the first null:
    // user?.address?.city ?: "unknown"
}
Kotlin
fun describe(input: String?) {
    // Smart cast: after the null check, the compiler
    // treats 'input' as non-null String inside the block.
    if (input != null) {
        println("length is ${input.length}")   // no ?. needed
    }

    // let: run a block only when non-null:
    input?.let { s ->
        println("got: $s")
    }
}

fun main() {
    // !! asserts 'trust me, not null' — crashes if wrong:
    val risky: String? = null
    // val boom = risky!!.length   // NullPointerException
⚠ Warning
Every !! in your code is a place you've told the compiler to stop protecting you. Treat it as a code smell — there's almost always a ?. / ?: / let shape that expresses the intent safely.