Null Safety

Kotlin's defining feature: String can never hold null, only String? can — and ?. and ?: let you work with a nullable value safely instead of crashing.

Nullable types

This is Kotlin's headline feature. A regular type like String can never hold null — the compiler simply won't let you assign it. To allow null, you write String?, explicitly marking the type as nullable:

</> main.kt
fun main() {
    var name: String = "Priya"
    // name = null        // would not compile: Null can not be a value of a non-null type String

    var nickname: String? = "P"
    nickname = null      // fine — the type says this is allowed

    println(nickname)
}
Output
null

The type system tracks this distinction everywhere. Because name: String can never be null, calling name.length is always safe and needs no null check — an entire category of Java's NullPointerException simply becomes impossible to compile.

The safe call operator ?.

For a nullable type, calling a method directly (nickname.length) won't compile — the compiler forces you to handle the null case. The safe call operator ?. returns null automatically instead of crashing if the value is null:

</> main.kt
fun main() {
    val nickname: String? = null
    val length = nickname?.length

    println(length)
}
Output
null

The Elvis operator ?: for a fallback

Chain ?: after a safe call to supply a default value when the result would otherwise be null:

</> main.kt
fun main() {
    val nickname: String? = null
    val length = nickname?.length ?: 0

    println("Length: $length")
}
Output
Length: 0

Read a ?: b as "a, or b if a is null" — it's the closest thing Kotlin has to a null-coalescing operator, and it's everywhere in idiomatic Kotlin code.

The !! operator — use sparingly: !! force-unwraps a nullable value, asserting to the compiler "trust me, this isn't null" — and if you're wrong, it throws a NullPointerException at runtime, the exact crash null safety exists to prevent. Reaching for !! regularly is usually a sign the code should use ?. and ?: instead, or restructure so the value's non-nullability is provable rather than asserted.