Question #371MediumNative Android

How does null safety work in Kotlin?

#kotlin#null-safety

Answer

Overview

Kotlin's null safety prevents

text
NullPointerException
at compile-time.


Nullable vs Non-Nullable Types

kotlin
// Non-nullable (default)
var name: String = "Alice"
name = null // ❌ Compile error

// Nullable (with ?)
var nullableName: String? = "Bob"
nullableName = null // ✅ Allowed

Safe Call Operator (
text
?.
)

kotlin
val name: String? = null

// Unsafe
val length = name.length // ❌ Compile error

// Safe call
val length = name?.length // ✅ Returns null

Elvis Operator (
text
?:
)

kotlin
val name: String? = null
val displayName = name ?: "Guest" // Provide default

Not-Null Assertion (
text
!!
)

kotlin
val name: String? = getName()
val length = name!!.length // ⚠️ Throws if null

Safe Casts

kotlin
val obj: Any = "Hello"
val str: String? = obj as? String // Safe cast

Null Checks

kotlin
val name: String? = getName()

if (name != null) {
    println(name.length) // Smart cast to String
}

// let function
name?.let {
    println(it.length)
}

Best Practice: Use

text
?.
and
text
?:
instead of
text
!!
to avoid crashes.