0
0
Kotlinprogramming~5 mins

Null safety in collections in Kotlin

Choose your learning style9 modes available
Introduction

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 allowed
val 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.