Null safety helps avoid errors by making sure collections handle null values safely.
When you want to store only non-null items in a list or set.
When you need to allow some items in a collection to be null.
When you want to avoid crashes caused by null values in collections.
When you want to clearly show if a collection can hold nulls or not.
When working with data that might be missing or optional.
Syntax
Kotlin
val list: List<String> = listOf("a", "b") // no nulls allowedval listWithNulls: List<String?> = listOf("a", null, "b") // nulls allowed
Use Type? to allow nulls in collection elements.
Without ?, elements cannot be null.
Examples
A list of integers that cannot contain null values.
Kotlin
val numbers: List<Int> = listOf(1, 2, 3)
A list of integers where some elements can be null.
Kotlin
val nullableNumbers: List<Int?> = listOf(1, null, 3)
A set of strings that allows null values.
Kotlin
val set: Set<String?> = setOf("apple", null, "banana")
Sample Program
This program shows two lists: one that does not allow nulls and one that does. It prints each item, showing how to check for nulls safely.
Kotlin
fun main() {
val fruits: List<String> = listOf("apple", "banana", "cherry")
val fruitsWithNulls: List<String?> = listOf("apple", null, "banana")
println("Fruits without nulls:")
for (fruit in fruits) {
println(fruit)
}
println("\nFruits with possible nulls:")
for (fruit in fruitsWithNulls) {
if (fruit != null) {
println(fruit)
} else {
println("null found")
}
}
}
OutputSuccess
Important Notes
Use Type? inside collections to allow null elements.
Always check for null before using nullable elements to avoid errors.
Null safety helps prevent crashes caused by unexpected null values.
Summary
Collections can hold either non-null or nullable elements.
Use Type? to allow nulls in collection elements.
Check for nulls when working with nullable collections to keep your program safe.
Practice
(1/5)
1. What does Kotlin's null safety feature ensure when working with collections like List or Set?
easy
A. It prevents storing null values in collections declared without nullable types.
B. It automatically converts all null values to empty strings in collections.
C. It allows null values in any collection without restrictions.
D. It disables the use of collections if they contain null values.
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 hold null values.
Step 2: Apply this to collection elements
If a collection is declared as List<String>, it cannot contain null. To allow null, it must be declared as List<String?>.
Final Answer:
It prevents storing null values in collections declared without nullable types. -> Option A
Quick Check:
Null safety = no null in non-nullable collections [OK]
Hint: Non-nullable collections disallow null elements [OK]
Common Mistakes:
Assuming all collections allow null by default
Confusing null safety with automatic null replacement
Thinking null safety disables collections with nulls
2. Which of the following is the correct way to declare a list that can hold nullable integers in Kotlin?
easy
A. val numbers: List<Int> = listOf(1, 2, null)
B. val numbers: List<Int> = listOf(null, null, null)
C. val numbers: List = listOf(1, 2, 3)
D. val numbers: List = listOf(1, 2, null)
Solution
Step 1: Identify nullable type declaration
To allow null in a list, the element type must be nullable, written as Int?.
Step 2: Check list initialization
listOf(1, 2, null) is valid only if the list type is List<Int?>. val numbers: List = listOf(1, 2, null) matches this.
Final Answer:
val numbers: List<Int?> = listOf(1, 2, null) -> Option D
Quick Check:
Nullable type uses Int? for null elements [OK]
Hint: Use Type? to allow nulls in collections [OK]
Common Mistakes:
Declaring list as List<Int> but adding nulls
Using List<Int> with null elements causes error
Confusing nullable element type with nullable list
3. What will be the output of the following Kotlin code?
val list: List = listOf("apple", null, "banana")
val filtered = list.filterNotNull()
println(filtered)
medium
A. ["apple", null, "banana"]
B. [null]
C. ["apple", "banana"]
D. Compilation error
Solution
Step 1: Understand filterNotNull() behavior
This function removes all null elements from a collection, returning a list of non-null elements.
Step 2: Apply filterNotNull() on the list
Original list has "apple", null, "banana". After filtering, only "apple" and "banana" remain.
Final Answer:
["apple", "banana"] -> Option C
Quick Check:
filterNotNull() removes nulls [OK]
Hint: filterNotNull() removes all nulls from collections [OK]
Common Mistakes:
Expecting nulls to remain after filterNotNull()
Thinking filterNotNull() causes compile error
Confusing filterNotNull() with filter()
4. Identify the error in this Kotlin code snippet:
val list: List<Int> = listOf(1, 2, null, 4)
medium
A. The list declaration syntax is incorrect.
B. The list cannot contain null because Int is non-nullable.
C. The listOf function cannot be used with integers.
D. There is no error; the code compiles fine.
Solution
Step 1: Check element type and values
The list is declared as List<Int>, which means elements cannot be null.
Step 2: Identify the presence of null
The list contains a null value, which is not allowed for non-nullable types, causing a compilation error.
Final Answer:
The list cannot contain null because Int is non-nullable. -> Option B
Quick Check:
Non-nullable list disallows null elements [OK]
Hint: Non-nullable types disallow null values in collections [OK]
Common Mistakes:
Assuming null is allowed in List<Int>
Thinking listOf syntax is wrong
Ignoring Kotlin's null safety rules
5. Given a list of nullable strings 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?
hard
A. items.filterNotNull().associateWith { it.length }
B. items.associateWith { it!!.length }
C. items.associate { it to it.length }
D. items.map { it.length }.toMap()
Solution
Step 1: Remove null values safely
Use filterNotNull() to exclude null elements before mapping.
Step 2: Create map with strings as keys and lengths as values
Use associateWith { it.length } on the filtered list to map each string to its length.
Final Answer:
items.filterNotNull().associateWith { it.length } -> Option A
Quick Check:
Filter nulls first, then associate [OK]
Hint: Filter nulls before mapping to avoid errors [OK]
Common Mistakes:
Using !! operator risking NullPointerException
Trying to associate null keys or values
Mapping lengths without filtering nulls first
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.