What if a tiny null value could silently break your whole app? Let's stop that from happening!
Why Null safety in collections in Kotlin? - Purpose & Use Cases
Imagine you have a list of names, but some entries might be missing or accidentally set to null. You try to print each name, but suddenly your program crashes because it encounters a null value.
Manually checking each item for null before using it is slow and easy to forget. This leads to crashes or bugs that are hard to find. It's like walking on a path full of hidden holes--you might fall anytime.
Null safety in collections means the language helps you avoid these hidden holes by making sure you handle nulls properly. It forces you to think about nulls upfront, so your program stays safe and smooth.
val names: List<String?> = listOf("Alice", null, "Bob") names.forEach { if (it != null) println(it) }
val names: List<String> = listOfNotNull("Alice", null, "Bob") names.forEach { println(it) }
It lets you write safer, cleaner code that won't crash unexpectedly because of null values in your collections.
When building a contact list app, null safety ensures you don't accidentally show empty or broken entries, keeping the app reliable and user-friendly.
Manual null checks in collections are error-prone and tedious.
Null safety helps catch null issues early and keeps code clean.
It makes programs more reliable and easier to maintain.
Practice
List or Set?Solution
Step 1: Understand Kotlin's null safety in collections
Kotlin distinguishes between nullable and non-nullable types. Collections declared with non-nullable types cannot holdnullvalues.Step 2: Apply this to collection elements
If a collection is declared asList<String>, it cannot containnull. To allownull, it must be declared asList<String?>.Final Answer:
It prevents storingnullvalues in collections declared without nullable types. -> Option AQuick Check:
Null safety = nonullin non-nullable collections [OK]
- Assuming all collections allow null by default
- Confusing null safety with automatic null replacement
- Thinking null safety disables collections with nulls
Solution
Step 1: Identify nullable type declaration
To allownullin a list, the element type must be nullable, written asInt?.Step 2: Check list initialization
listOf(1, 2, null)is valid only if the list type isList<Int?>. val numbers: List = listOf(1, 2, null) matches this.Final Answer:
val numbers: List<Int?> = listOf(1, 2, null) -> Option DQuick Check:
Nullable type usesInt?for null elements [OK]
Type? to allow nulls in collections [OK]- Declaring list as
List<Int>but adding nulls - Using
List<Int>with null elements causes error - Confusing nullable element type with nullable list
val list: List = listOf("apple", null, "banana")
val filtered = list.filterNotNull()
println(filtered)Solution
Step 1: Understand
This function removes allfilterNotNull()behaviornullelements from a collection, returning a list of non-null elements.Step 2: Apply
Original list has "apple", null, "banana". After filtering, only "apple" and "banana" remain.filterNotNull()on the listFinal Answer:
["apple", "banana"] -> Option CQuick Check:
filterNotNull()removes nulls [OK]
- Expecting nulls to remain after filterNotNull()
- Thinking filterNotNull() causes compile error
- Confusing filterNotNull() with filter()
val list: List<Int> = listOf(1, 2, null, 4)
Solution
Step 1: Check element type and values
The list is declared asList<Int>, which means elements cannot benull.Step 2: Identify the presence of
The list contains anullnullvalue, which is not allowed for non-nullable types, causing a compilation error.Final Answer:
The list cannot containnullbecauseIntis non-nullable. -> Option BQuick Check:
Non-nullable list disallows null elements [OK]
- Assuming
nullis allowed inList<Int> - Thinking
listOfsyntax is wrong - Ignoring Kotlin's null safety rules
val items: List = listOf("a", null, "b", null, "c"), how can you create a map where keys are the strings and values are their lengths, excluding null values safely?Solution
Step 1: Remove null values safely
UsefilterNotNull()to excludenullelements before mapping.Step 2: Create map with strings as keys and lengths as values
UseassociateWith { it.length }on the filtered list to map each string to its length.Final Answer:
items.filterNotNull().associateWith { it.length } -> Option AQuick Check:
Filter nulls first, then associate [OK]
- Using !! operator risking NullPointerException
- Trying to associate null keys or values
- Mapping lengths without filtering nulls first
Ready to prove it?
Pass the test and this pattern moves unknown
