0
0
Kotlinprogramming~3 mins

Why Nullable types with ? suffix in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could avoid crashes just by knowing when something might be missing?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
val phoneNumber: String = getFriendNumber()
// crashes if number is missing
After
val phoneNumber: String? = getFriendNumber()
// safely handles missing number
What It Enables

You can write safer programs that clearly handle missing or optional data without unexpected crashes.

Real Life Example

When building a contact app, some contacts might not have an email address. Using nullable types lets you store and check for emails safely.

Key Takeaways

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.