Skip to content
The App Code
Concept

Null Safety in Kotlin

A type system that distinguishes nullable from non-nullable references to eliminate most null-pointer exceptions.

Also known as: Kotlin nullable types, Kotlin NPE prevention

beginner

In Kotlin, String can never be null but String? can. The compiler forces you to handle the nullable case before dereferencing, catching NPEs at compile time.

What it is

Kotlin bakes nullability into its type system. A plain String is guaranteed non-null; to allow null you write String?. The compiler then refuses to let you call methods on a nullable reference without first proving it isn't null, moving a whole class of NullPointerException bugs from runtime to compile time.

The key operators are the safe call ?. (returns null instead of throwing), the Elvis operator ?: (provides a fallback), and the not-null assertion !! (throws if null). Smart casts also help: after an if (x != null) check, the compiler treats x as non-null inside that block.

Worked example

fun greet(name: String?): String {
    // Safe call + Elvis fallback
    val length = name?.length ?: 0

    return if (name != null) {
        "Hello, $name ($length chars)" // smart cast: name is String here
    } else {
        "Hello, stranger"
    }
}

fun main() {
    println(greet("Ada"))  // Hello, Ada (3 chars)
    println(greet(null))   // Hello, stranger
}

Failure mode — when it misleads

The !! operator re-introduces the exact runtime NPE Kotlin is designed to prevent, so treat every !! as a code smell. Also, values coming from Java have "platform types" the compiler can't check, so a Java method annotated as non-null can still hand you null — validate at the boundary.

Sources & further reading