What if your program could avoid crashes just by knowing when something might be missing?
Why Nullable types with ? suffix in Kotlin? - Purpose & Use Cases
Imagine you have a list of friends' phone numbers, but some friends haven't shared their number yet. You try to write code that assumes every friend has a number, but sometimes the number is missing.
Without a clear way to say "this value might be missing," your program crashes or behaves unpredictably when it encounters a missing number. You have to write many checks everywhere, making your code messy and error-prone.
Nullable types with the ? suffix let you clearly say "this value can be missing." The language then forces you to handle these cases safely, preventing crashes and making your code cleaner and more reliable.
val phoneNumber: String = getFriendNumber()
// crashes if number is missingval phoneNumber: String? = getFriendNumber() // safely handles missing number
You can write safer programs that clearly handle missing or optional data without unexpected crashes.
When building a contact app, some contacts might not have an email address. Using nullable types lets you store and check for emails safely.
Nullable types explicitly mark values that can be missing.
This prevents many common errors and crashes.
It makes your code clearer and easier to maintain.