Quick Answer
Handling nullable types safely
Understanding the Issue
Kotlin's type system distinguishes nullable from non-nullable types. Safe calls (?.), Elvis operator (?:), and non-null assertions (!!) help handle null cases explicitly.
The Problem
This code demonstrates the issue:
Kotlin
Error
// Problem: Unsafe null usage
val length: Int = nullableString.length // Error
The Solution
Here's the corrected code:
Kotlin
Fixed
// Solution 1: Safe call
val length: Int? = nullableString?.length
// Solution 2: Elvis operator
val length: Int = nullableString?.length ?: 0
// Solution 3: Non-null assertion (only when sure)
val length: Int = nullableString!!.length
Key Takeaways
Always handle null cases explicitly using Kotlin's null safety operators.