Kotlin

Nullable Types — String? and the ? Operator

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Kotlin distinguishes `String` (never null) from `String?` (may be null) in the type system. The compiler refuses to compile code that could deref a possibly-null value — the famous "no more NullPointerException" feature.
Kotlin
Raw
fun main() {
    val name: String  = "Alice"        // never null
    val maybe: String? = null          // explicitly nullable

    // name.length        // OK — compiler knows it can't be null
    // maybe.length       // ✗ compile error: receiver may be null

    // Three ways to handle the nullable safely:

    // 1. Safe call ?. — returns null if receiver is null
    val len: Int? = maybe?.length
    println(len)                         // null

    // 2. Elvis ?: — supply a fallback
    val len2: Int = maybe?.length ?: 0
    println(len2)                        // 0

    // 3. Not-null assertion !! — throws NPE if null (use sparingly)
    val len3: Int = maybe!!.length       // NullPointerException here

    // 4. Smart cast after a null check
    if (maybe != null) {
        println(maybe.length)            // smart-cast to non-null String
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.