Mobile Development
Kotlin
Subjective
Oct 04, 2025
What is null safety in Kotlin and why is it important?
Detailed Explanation
Null safety is Kotlin's system to eliminate NullPointerException at compile time:\n\n1. Non-nullable Types (Default)\n• Variables cannot hold null by default\n• Example: var name: String = "John" // Cannot be null\n\n2. Nullable Types (Explicit)\n• Must explicitly allow null with ?\n• Example: var name: String? = null // Can be null\n\n3. Safe Call Operator (?.)\n• Safely access nullable properties\n• Returns null if receiver is null\n• Example: val length = name?.length\n\n4. Elvis Operator (?:)\n• Provides default value for null cases\n• Example: val length = name?.length ?: 0\n\n5. Not-null Assertion (!!)\n• Forces unwrap (use carefully)\n• Throws exception if null\n• Example: val length = name!!.length\n\n6. Safe Casting (as?)\n• Returns null if cast fails\n• Example: val str = obj as? String\n\n7. Why Important\n• Eliminates most common runtime error\n• Makes null handling explicit\n• Improves code reliability
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts