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.
Practice
? after a type in Kotlin mean?Solution
Step 1: Understand Kotlin type suffix
In Kotlin, adding?after a type means the variable can hold null.Step 2: Compare with non-nullable types
Without?, variables cannot be null and will cause errors if assigned null.Final Answer:
The variable can hold a null value. -> Option BQuick Check:
Nullable type = variable can be null [OK]
? means nullable type in Kotlin [OK]- Thinking
?makes variable immutable - Confusing
?with constant declaration - Assuming
?means function type
Solution
Step 1: Recall Kotlin nullable syntax
Kotlin uses?after the type name to mark it nullable, e.g.,String?.Step 2: Check each option
var name: String? usesString?correctly. Options A, B, and D use invalid syntax.Final Answer:
var name: String? -> Option AQuick Check:
Nullable syntax = type followed by?[OK]
? right after the type name for nullable [OK]- Placing
?before the type - Using
!instead of? - Writing 'nullable' keyword explicitly
var text: String? = null println(text?.length ?: "No length")
Solution
Step 1: Understand safe call and Elvis operator
text?.lengthsafely accesses length if text is not null; else returns null. The Elvis operator?:provides "No length" if left side is null.Step 2: Evaluate given code
Sincetextis null,text?.lengthis null, so the expression prints "No length".Final Answer:
No length -> Option CQuick Check:
Safe call + Elvis = fallback value [OK]
- Expecting NullPointerException on null safe call
- Thinking null?.length returns 0
- Ignoring Elvis operator fallback
var number: Int? = 10 var result: Int = number + 5
Solution
Step 1: Check type compatibility
numberis nullableInt?, butresultexpects non-nullInt. Adding nullable and non-null directly is not allowed.Step 2: Understand Kotlin's null safety
You must safely unwrapnumberbefore adding, e.g., usingnumber ?: 0or safe call.Final Answer:
Cannot add Int? and Int directly. -> Option DQuick Check:
Nullable + non-null Int needs safe unwrap [OK]
- Assuming nullable Int can be used like Int
- Ignoring need for safe call or Elvis operator
- Thinking semicolon is required in Kotlin
val items: List?. How do you safely print the length of the first item or print 0 if the list or first item is null?Solution
Step 1: Analyze nullable types
itemscan be null, and its elements can be null. So both list and first item need safe calls.Step 2: Use safe calls and Elvis operator
items?.get(0)?.length ?: 0safely accesses first item length or returns 0 if null.Final Answer:
println(items?.get(0)?.length ?: 0) -> Option AQuick Check:
Safe calls chain + fallback = safe nullable access [OK]
- Using !! which throws exception if null
- Missing safe call on first item
- Assuming list or item can't be null
Ready to prove it?
Pass the test and this pattern moves unknown
