Answer
Overview
Kotlin's null safety prevents
text
NullPointerExceptionNullable 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?.
)
text
?.kotlinval name: String? = null // Unsafe val length = name.length // ❌ Compile error // Safe call val length = name?.length // ✅ Returns null
Elvis Operator (text?:
)
text
?:kotlinval name: String? = null val displayName = name ?: "Guest" // Provide default
Not-Null Assertion (text!!
)
text
!!kotlinval name: String? = getName() val length = name!!.length // ⚠️ Throws if null
Safe Casts
kotlinval obj: Any = "Hello" val str: String? = obj as? String // Safe cast
Null Checks
kotlinval name: String? = getName() if (name != null) { println(name.length) // Smart cast to String } // let function name?.let { println(it.length) }
Best Practice: Use
andtext?.instead oftext?:to avoid crashes.text!!