Skip to content
Kotlin

Null Safety

Use nullable types, safe calls, Elvis, and smart casts for null-safe code.

By EZ4Code Team
null-safetynullable

Code

// Nullable types
var name: String? = "Alice"
name = null

// Safe call
println(name?.length)

// Elvis operator for default
val len = name?.length ?: 0
println(len)

// Smart cast after null check
fun greet(who: String?) {
    if (who != null) {
        println("Hi $who, length=${who.length}")  // smart-cast to String
    } else {
        println("No name")
    }
}
greet("Bob")
greet(null)

// let for null-scoped work
name?.let { println("Got $it") }

// Not-null assertion (use sparingly)
// val forced = name!!

// Nullable receivers
fun String?.orEmpty(): String = this ?: ""

// lateinit for deferred non-null init
class Service {
    lateinit var url: String
    fun init() { url = "https://api.example.com" }
}

val svc = Service()
svc.init()
println(svc.url)

Explanation

Kotlin separates nullable types with ? from non-null types, forcing the compiler to track nullability. Safe calls ?. and the Elvis operator ?: provide defaults without explicit checks. After an if-null check the compiler smart-casts the value to its non-null type, removing the need for redundant assertions.

More Kotlin Snippets