SyntaxStudy
Sign Up
Kotlin Nullable Types and the Safe-Call Operator
Kotlin Beginner 1 min read

Nullable Types and the Safe-Call Operator

In Kotlin, every type is non-nullable by default. Attempting to assign null to a plain String variable is a compile-time error. To allow null you append a question mark: String? means a string that may be null. The safe-call operator ?. lets you access properties or call methods on a nullable value without a NullPointerException: the entire expression evaluates to null if the receiver is null. You can chain multiple safe calls together, and the whole chain short-circuits at the first null. The Elvis operator ?: provides a default value when the left-hand side is null, removing the need for verbose null checks. The not-null assertion operator !! forces a nullable value to non-null, throwing a KotlinNullPointerException if it actually is null — use it only when you are certain the value cannot be null.
Example
fun findUser(id: Int): String? {
    return if (id == 1) "Alice" else null
}

fun main() {
    val user: String? = findUser(2)   // may be null

    // Safe call — returns null if user is null
    val length: Int? = user?.length
    println("Length: $length")        // Length: null

    // Elvis operator — supply a default
    val displayName = user ?: "Guest"
    println("Hello, $displayName!")   // Hello, Guest!

    // Chained safe calls
    val city: String? = null
    val upper = city?.trim()?.uppercase()
    println("City: $upper")           // City: null

    // Not-null assertion (use sparingly)
    val known: String? = "Kotlin"
    println(known!!.length)           // 6

    // let block — runs only when non-null
    user?.let {
        println("User found: $it, length=${it.length}")
    }

    // Null check with smart cast
    if (user != null) {
        println(user.uppercase())     // user is String here
    }
}